Arrow function (=>)
A short way to write a function.
Available since: ES2015
Syntax
(params) => expression / (params) => { … }Examples
The short form returns the expression's result:
const double = (n) => n * 2;
console.log(double(4));Output:
8A body in curly braces needs return:
const sum = (a, b) => {
const result = a + b;
return result;
};
const makeUser = (name) => ({ name });
console.log(sum(2, 3));
console.log(makeUser('Anna').name);Output:
5
AnnaAn arrow function takes this from outside:
const timer = {
seconds: 3,
start() {
[1, 2].forEach(() => {
console.log(this.seconds);
});
},
};
timer.start();Output:
3
3Notes
To return an object in the short form wrap it in parentheses: () => ({ a: 1 }), otherwise the braces are taken as the function body.
An arrow function has no own this or arguments and cannot be called with new. That is why object methods usually use regular method syntax.
See also
- Default parameters — A parameter's value when no argument is passed.
- Rest parameters — Collects the remaining function arguments into an array.
- Function.prototype.bind — Creates a copy of a function with a fixed this and, optionally, arguments.
In the tutorial
- Arrow functions — Function expressions and arrow functions in JavaScript — the short form, implicit return and a body in curly braces.