JavaScript Arrow Functions
Arrow functions are a shorter way to write functions. They came with ES6 (2015) and are used everywhere in modern JavaScript.
From a normal function to an arrow function
// normal function
const add = function (a, b) {
return a + b;
};
// arrow function
const add2 = (a, b) => {
return a + b;
};
// shortest: one expression, "return" is implied
const add3 = (a, b) => a + b;
console.log(add(2, 3), add2(2, 3), add3(2, 3));
Output of the above program is
5 5 5
Syntax rules
| Case | Syntax |
|---|---|
| No parameters | () => "Hi" |
| One parameter | n => n * 2 (brackets optional) |
| Many parameters | (a, b) => a + b |
| Many statements | (a, b) => { ... return x; } |
| Return an object | () => ({ name: "Robin" }) (wrap in brackets) |
Arrow functions with array methods
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
const even = numbers.filter(n => n % 2 === 0);
console.log(doubled);
console.log(even);
Output of the above program is
[ 2, 4, 6, 8 ]
[ 2, 4 ]
this in arrow functions
A normal function has its own this. An arrow function does not: it uses the this of the place where it was written. So do not use an arrow function as a method of an object. Read the this keyword.
Note:
Arrow functions also cannot be used as constructors (with new) and have no arguments object.
Summary
(params) => expressionis the short syntax with an implied return.- They are perfect for callbacks like
mapandfilter. - They do not have their own
this. - Next: JavaScript Arrays.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |