Javascript arrow function is defined as follows:
let arrowSum = (a, b) => { return a + b; /*from w ww. j a v a 2s . c o m*/ }; //The same function defined in tranditional way. let functionExpressionSum = function(a, b) { return a + b; }; console.log(arrowSum(5, 8)); // 13 console.log(functionExpressionSum(5, 8)); // 13
Arrow functions are used inline.
let ints = [1, 2, 3]; console.log(ints.map(function(i) { return i + 1; })); // [2, 3, 4] console.log(ints.map((i) => { return i + 1 })); // [2, 3, 4]
Arrow functions do not require the parentheses for a single parameter.
To have zero or more than one parameter, parentheses are required:
// Both are valid let double = (x) => { return 2 * x; }; let triple = x => { return 3 * x; };
Zero parameters require an empty pair of parentheses
let getRandom = () => { return Math.random(); };
Multiple parameters require parentheses
let sum = (a, b) => { return a + b; };
For single line function body we can omit the curly braces.
Both are valid and will return the value
let double = (x) => { return 2 * x; }; let triple = (x) => 3 * x;
Assignment is allowed
let value = {}; //from www .j a v a2s. c o m let setName = (x) => x.name = "CSS"; setName(value); console.log(value.name); // "CSS"