Arrow functions are shorthand for an anonymous function that keep the current context. example:
const a = 2;
const multiply = function (num) {
return num * a;
}.bind(this);
console.log(multiply(3)) //=> 6
Can be written as:
const a = 2;
const multiply = num => num * a;
console.log(multiply(3)) //=> 6
This is most useful for cases like map or reduce:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(number => number * 2);
console.log(doubled);//=> [2, 4, 6, 8]
Arrow function syntax
Arrow functions take the following form:(<arguments>) => <return statement>
. for more here.
When there is only a single argument, the parens are optional e.g.(x) => x * x and x => x * x
are both valid. When there are 0 or 2 or more arguments, parens are required. e.g.() => 'blah' or (x, y) => x * y
For multiline statements wrap the function body in curly braces:
const numbers = [1, 2, 3, 4];
const cubed = numbers.map(number => {
const squared = number * number;
return squared * number;
});
console.log(cubed);//=> [1, 8, 27, 64]