An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
// ES5
var multiplyES5 = function(x, y) {
return x * y;
};
const multiplyES6 = (x, y) => x * y;
//ES5
var phraseSplitterEs5 = function phraseSplitter(phrase) {
return phrase.split(' ');
};
//ES6
const phraseSplitterEs6 = phrase => phrase.split(" ");
console.log(phraseSplitterEs6("ES6 Awesomeness")); // ["ES6", "Awesomeness"]
let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }
alert( double(3) ); // 6
//ES5
var docLogEs5 = function docLog() {
console.log(document);
};
//ES6
var docLogEs6 = () => { console.log(document); };
docLogEs6(); // #document... <html> ....
Return an object literal expression.
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return {
id: id,
name: name
};
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
console.log(setNameIdsEs6 (4, "Kyle")); // Object {id: 4, name: "Kyle"}
const smartPhones = [
{ name:'iphone', price:649 },
{ name:'Galaxy S6', price:576 },
{ name:'Galaxy Note 5', price:489 }
];
// ES5
var prices = smartPhones.map(function(smartPhone) {
return smartPhone.price;
});
console.log(prices); // [649, 576, 489]
// ES6
const prices = smartPhones.map(smartPhone => smartPhone.price);
console.log(prices); // [649, 576, 489]
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
// ES5
var divisibleByThrreeES5 = array.filter(function (v){
return v % 3 === 0;
});
// ES6
const divisibleByThrreeES6 = array.filter(v => v % 3 === 0);
console.log(divisibleByThrreeES6); // [3, 6, 9, 12, 15]
Arrow functions, introduced in ES6, provide a concise syntax for writing function expressions, offering a clear and modern alternative to traditional ES5 functions. They simplify code and improve readability, especially in cases with simple, single-line expressions. However, it's essential to remember that arrow functions have limitations, such as not having their own this context, which can make them unsuitable for certain scenarios like object methods or constructors neal fun. Overall, arrow functions are a powerful tool in JavaScript, enhancing the language's expressiveness and helping developers write cleaner code.
Overall, arrow functions offer a more elegant and concise syntax for writing functions, particularly in scenarios where brevity and readability are essential. However, it's important to note that arrow functions have some limitations strands compared to traditional function expressions, such as the inability to bind their value.