Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

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:

8

A 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
Anna

An arrow function takes this from outside:

const timer = {
  seconds: 3,
  start() {
    [1, 2].forEach(() => {
      console.log(this.seconds);
    });
  },
};
 
timer.start();

Output:

3
3

Notes

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

In the tutorial

  • Arrow functions — Function expressions and arrow functions in JavaScript — the short form, implicit return and a body in curly braces.

Thanks for reading!

Donate to the site — we work hard for you.