Arrow functions

JavaScript · Essentials · 8 min

Arrows are the default way to write callbacks in modern code.

An arrow function is a shorter function expression:

const double = (n) => n * 2;

The rules for the short forms:

  • One parameter: parentheses are optional (n => n * 2); zero or several need them (() => 42, (a, b) => a + b).
  • If the body is a single expression without braces, its value is returned implicitly.
  • With braces, it's a normal block and you need an explicit return.
  • To implicitly return an object literal, wrap it in parentheses: () => ({ id: 1 }). Without them, the braces are read as a block and id: 1 as a label, so the function returns undefined.

Arrows shine as callbacks: prices.map(p => p * 1.2), setTimeout(() => save(), 500).

They are not just syntax sugar, though. Arrow functions:

  • have no own this — they use the this of the surrounding code, which is exactly what you want in callbacks inside methods;
  • have no own arguments object (use rest parameters);
  • cannot be called with new and have no prototype.

Because of the this behaviour, don't use an arrow as an object method that needs to refer to its object; use method syntax ({ total() { return this.a + this.b; } }) instead. You'll see the full this rules in a later lesson.

A common style is: function declarations for named, top-level functions, and arrows for short inline callbacks.

Example

const add = (a, b) => a + b;
const shout = s => s.toUpperCase() + "!";
const makeUser = name => ({ name, createdAt: 2025 }); // parens for object

console.log(add(2, 3));          // 5
console.log(shout("hey"));       // HEY!
console.log(makeUser("Ada"));    // { name: 'Ada', createdAt: 2025 }

const broken = () => { id: 1 };  // block with a label, not an object
console.log(broken());           // undefined

const prices = [10, 20, 30];
const withTax = prices.map(p => {
  const tax = p * 0.2;
  return p + tax;                // braces need explicit return
});
console.log(withTax);            // [ 12, 24, 36 ]

Remember

  • x => expr returns expr implicitly; a braced body needs return
  • Wrap object literals in parentheses: () => ({ ... })
  • Arrows have no own this, arguments or prototype and can't be used with new

Watch out for

  • Using an arrow function as an object method and finding this isn't the object.

Check yourself

  1. What does (() => { value: 1 })() return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions