Arrow (=>
) function expressions are shorter syntax compared to function expressions. Arrow functions are always anonymous. Here are some commonly used usage syntax patterns.
singleParam => expression singleParam => { statements } (param1, param2, …, paramN) => expression (param1, param2, …, paramN) => { statements }
Assigning arrow function to a variable
var inc = x => x+1; console.log("inc(3)= " + inc(3));
inc(3)= 4
Env: node version v10.24.1
arrow function to increment array values by 1
arr = [1, 3, 8]; newArr = arr.map(x => x+1); console.log("newArr=" + newArr);
newArr=2,4,9
Env: node version v10.24.1
Same thing with slightly different syntax:
arr = [1, 3, 8]; newArr = arr.map(x => {console.log("x="+x); return x+1}); console.log("newArr=" + newArr);
x=1 x=3 x=8 newArr=2,4,9
Env: node version v10.24.1
arrow function with two args
Set array value as 0 if index is even.
arr = [1, 3, 8, 2, 5]; newArr = arr.map((x,i) => (i%2==0)? 0: x); console.log("newArr=" + newArr);
newArr=0,3,0,2,0
Env: node version v10.24.1
Browser support
Note that Arrow function are not supported in IE.