JavaScript Tutorial · Functions · Lesson 19 of 44

JavaScript Arrow Functions

The short => syntax, implicit returns and how arrows treat this.

Arrow syntax

Arrow functions are a shorter way to write function expressions:

Example 1Try it yourself
const double = (x) => x * 2;
const add = (a, b) => a + b;
const makeUser = (name) => ({ name, active: true });
const sayHi = () => {
  const msg = "Hi!";
  return msg;
};
console.log(double(5), add(2, 3), sayHi());
console.log(makeUser("Ada"));

Output

10 5 Hi!
{ name: 'Ada', active: true }
  • With one parameter, the parentheses are optional: x => x * 2.
  • With an expression body (no braces), the value is returned automatically.
  • To return an object literal, wrap it in parentheses: () => ({ ok: true }).

Arrows as callbacks

Arrow functions shine when passing small functions to methods like map and filter:

Example 2Try it yourself
const prices = [5, 12, 8, 20];
console.log(prices.map((p) => p * 1.2));
console.log(prices.filter((p) => p > 10));

Output

[ 6, 14.399999999999999, 9.6, 24 ]
[ 12, 20 ]

Arrows and this

Arrow functions don't have their own this — they use the this of the surrounding code. That makes them ideal for callbacks inside methods, but you should not use them as object methods that need this:

Example 3Try it yourself
const counter = {
  count: 0,
  start() {
    [1, 2, 3].forEach(() => {
      this.count++;   // arrow uses start()'s this → counter
    });
    return this.count;
  },
};
console.log(counter.start());

Output

3

Test yourself

What does const f = x => ({ x }) return for f(1)?

  1. undefined
  2. 1
  3. { x: 1 }
  4. SyntaxError
Show answer

Answer: { x: 1 }

Parentheses around { x } make it an object literal instead of a function body.