Arrow functions

ES6 introduces arrow functions as a function shorthand, using => syntax. Arrow functions support statement block bodies as well as expression bodies. When using an expression body, the expression's result is the value that the function returns.

An arrow syntax begins with function arguments, then the arrow =>, and then the function body. Let's look at the following different variations of arrow functions. The examples are written in both ES5 syntax and ES6 arrow function syntax:

const fruits = [{name: 'apple', price: 100}, {name: 'orange', price: 80}, {name: 'banana', price: 120}];

// Variation 1
// When no arguments, an empty set of parentheses is required
var countFruits = () => fruits.length;
// equivalent to ES5
var countFruits = function () {
return fruits.length;
};

// Variation 2
// When there is one argument, parentheses can be omitted.
// The expression value is the return value of the function.
fruits.filter(fruit => fruit.price > 100);
// equivalent to ES5
fruits.filter(function(fruit) {
return fruit.price > 100;
});

// Variation 3
// The function returns an object literal, it needs to be wrapped
// by parentheses.
var inventory = fruits.map(fruit => ({name: fruit.name, storage: 1}));
// equivalent to ES5
var inventory = fruits.map(function (fruit) {
return {name: fruit.name, storage: 1};
});

// Variation 4
// When the function has statements body and it needs to return a
// result, the return statement is required
var inventory = fruits.map(fruit => {
console.log('Checking ' + fruit.name + ' storage');
return {name: fruit.name, storage: 1};
});
// equivalent to ES5
var inventory = fruits.map(function (fruit) {
console.log('Checking ' + fruit.name + ' storage');
return {name: fruit.name, storage: 1};
});

There is an additional note regarding variation 3. When an arrow function uses curly brackets, its function body needs to be a statement or statements:

var sum = (a, b) => { return a + b };
sum(1, 2); // 3

The sum function won't work as expected when it is written like this:

var sum = (a, b) => { a + b };
sum(1, 2); // undefined
// Using expression will work
var sum = (a, b) => a + b;
sum(1, 2); // 3

Arrow functions have a shorter syntax and also many other important differences compared with ES5 function. Let's go through some of these differences one by one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.80.101