Thuta Learning
JavaScript
AdvancedProgrammingBeginner

Arrow Functions

JavaScriptLesson 4125 min

What you'll walk away with

  • Rewrite a function expression as an arrow with the right syntax for zero, one or many parameters
  • Tell a concise body (implicit return) from a block body (explicit return) and return an object literal with parentheses
  • Explain why an arrow callback still sees the this of the method that contains it
  • Decide when a regular function is the better choice: object methods, constructors and code that needs arguments

Explain it simply

Explain it simply

JavaScript code is full of tiny functions: double every number in an array, react when a button is clicked, pick the active users from a list. Writing the function keyword, curly braces and return every single time adds noise that hides the one line of real work.

An arrow function lets you write those small functions in a single line. You read (n) => n * 2 as "take n and give back n * 2". It is not only shorter, though; it also behaves differently in one important way. An arrow function has no this of its own, so it keeps using the this of the code around it.

Problem → Why → Solution

The problem: this goes missing inside a callback

The start() method of a counter object calls forEach with a regular function callback. The author expects this inside the callback to be the counter. It is not: forEach calls the callback as a plain function, so this is not counter. In a module or strict-mode file this is undefined and the line throws a TypeError; in an old-style script it silently writes NaN to a global count instead.

The second bug is quieter. The author wants map to return objects and writes x => { value: x }. The result is [undefined, undefined], and no error appears at all.

counter.js
const counter = {
  count: 0,
  start() {
    [1, 2, 3].forEach(function () {
      this.count += 1; // TypeError: Cannot read properties of undefined
    });
  },
};
counter.start();

const items = [1, 2].map((x) => { value: x });
console.log(items); // [ undefined, undefined ]

Why does this happen?

Every regular function gets its own this, decided by how it is called. The forEach callback is not called as object.method(), so it knows nothing about counter. In the second bug, JavaScript reads the { after the arrow as the start of a function body, not an object. value: becomes a statement label, there is no return, and the result is undefined.

Core concept: the shapes and rules of arrow functions

An arrow function is a kind of function expression, so you usually assign it to a const or pass it straight into another function such as map, filter or setTimeout. It has two parts: the parameters on the left of => and the body on the right.

1. Parameters

With no parameters you write empty parentheses: () => .... A single parameter may drop them, x => ..., although many teams always write (x) => .... Two or more parameters, a default value or a destructuring pattern always need the parentheses.

2. Concise body or block body

If the right side is a single expression (a concise body), its value is returned automatically with no return keyword. If you open curly braces for several statements (a block body), it works like a normal function: you must write return yourself, or you get undefined.

3. Wrap an object literal in parentheses

JavaScript always reads a { right after => as a block body. To return an object, wrap it: (name) => ({ name }). The parentheses tell the parser "this is an expression".

4. this and arguments come from outside

An arrow has no this, arguments or super of its own; it uses the ones from the place where it is written. This is called lexical this. It is perfect for callbacks inside a method, but an arrow used as the method itself cannot see the object.

Regular functionArrow function
thisDepends on how it is calledTaken from where it is written
Called with newBuilds a new objectTypeError: ... is not a constructor
argumentsHas its ownNone; use ...rest instead
HoistingDeclarations can be called earlyLives in a const; call it after
Mental model: a function that borrows this
  1. Parameters go left of =>
  2. One expression returns by itself
  3. Braces mean you write return
  4. this comes from the outer scope

For an arrow, do not ask "who calls this function?". Ask "where is this code written?": that alone decides what this means.

General pattern

javascript
const noParams = () => expression;
const oneParam = (param) => expression;
const manyParams = (a, b = defaultValue) => expression;

const withBlock = (param) => {
  // several statements
  return result;
};

const makeObject = (key) => ({ key: key });

A single expression needs no return. As soon as you open braces, write return yourself. To give back an object, wrap it as ({ ... }).

Run the four shapes of an arrow function

The file below has four parts: the same function in two syntaxes, a concise body next to a block body, an object literal returned from an arrow, and an arrow callback that keeps the this of its method. Predict all four output lines before you run it.

arrow-functions.js
// 1. The same function in two syntaxes
const addOld = function (a, b) {
  return a + b;
};
const add = (a, b) => a + b;
console.log(addOld(2, 3), add(2, 3));

// 2. Concise body (implicit return) vs block body (explicit return)
const square = (n) => n * n;
const describe = (n) => {
  const kind = n % 2 === 0 ? "even" : "odd";
  return `${n} is ${kind}`;
};
console.log(square(4), describe(7));

// 3. Returning an object literal needs parentheses
const toItem = (name) => ({ name, done: false });
console.log(["milk", "eggs"].map(toItem));

// 4. An arrow callback uses `this` from the surrounding method
const timer = {
  seconds: 0,
  tickThreeTimes() {
    [1, 2, 3].forEach(() => {
      this.seconds += 1; // `this` is still timer
    });
    return this.seconds;
  },
};
console.log(timer.tickThreeTimes());

Code breakdown

  1. Same job, shorter syntaxconst add = (a, b) => a + b;

    The function keyword, the braces and return are gone, yet it does exactly what addOld does, so the first line prints 5 5.

  2. Block body needs returnreturn `${n} is ${kind}`;

    describe needs two statements, so it opens braces and must return explicitly. Delete this line and describe(7) becomes undefined.

  3. Object literal in parenthesesconst toItem = (name) => ({ name, done: false });

    The parentheses make { name, done: false } an object expression, so map(toItem) turns each string into an object.

  4. Lexical this in a callbackthis.seconds += 1; // `this` is still timer

    The callback is an arrow, so it has no this of its own and uses the this of tickThreeTimes(), which is timer. seconds climbs to 3.

  5. The method itself is not an arrowtickThreeTimes() {

    The method uses ordinary method shorthand. Called as timer.tickThreeTimes(), its this is timer, and the arrows inside borrow that this.

You should see
5 5
16 7 is odd
[ { name: 'milk', done: false }, { name: 'eggs', done: false } ]
3

Where an arrow is the wrong tool

Because arrows are shorter, it is tempting to use them everywhere. Their borrowed this is exactly what makes them wrong in a few places. An object method written as an arrow gets the this of the code surrounding the object literal, not the object. Calling an arrow with new throws a TypeError, and arrows have no prototype property.

A DOM event listener that relies on this being the clicked element also breaks with an arrow. The cleaner fix there is to keep the arrow and read event.currentTarget instead.

wrong-tool.js
const user = {
  name: "Ana",
  greetArrow: () => typeof this,        // not user
  greetMethod() { return this.name; },  // user
};
console.log(user.greetArrow(), user.greetMethod());

const Point = (x) => { this.x = x; };
try {
  new Point(1);
} catch (err) {
  console.log(err.message); // Point is not a constructor
}

Names in stack traces

An arrow assigned to a variable, like const add = () => ..., takes the variable's name as its function name. Inline arrows passed straight into map have no name and show up as anonymous in a stack trace. Pulling complex logic out into a named function makes errors easier to trace.

In real projects

In real projects

In today's JavaScript codebases you meet arrows most often in array pipelines. A chain like orders.filter((o) => o.paid).map((o) => o.total).reduce((sum, t) => sum + t, 0) reads as one small step per callback. Promise chains use them for short steps too, such as .then((res) => res.json()).

Inside classes, event handlers are often written as class-field arrows: handleClick = () => { ... }. Then you can pass this.handleClick straight to button.addEventListener("click", ...) and this still points at the instance, with no .bind(this) needed. Most React components you read are written with arrows as well.

The usual team rule is simple: arrows for callbacks and short helpers, regular functions or method syntax for object methods, class methods and a file's main named functions. Many teams turn on ESLint rules such as prefer-arrow-callback so the linter enforces that split automatically.

Common mistakes

Common mistakes

Opening braces and forgetting return

You start with (x) => x * 2, then add a log line and write (x) => { console.log(x); x * 2; }. The implicit return is gone and map now produces an array of undefined values. Every time you add braces, check for a return.

Returning an object without parentheses

items.map((x) => { value: x }) returns no objects, because the braces are read as a body and value: as a label. Write (x) => ({ value: x }). With two properties you would get a SyntaxError and notice, but with one property it fails silently.

Writing an object method as an arrow

In const cart = { items: [], count: () => this.items.length }, this is not cart. In a module it is undefined, so cart.count() throws a TypeError. Methods that need this belong in method syntax: count() { ... }.

Using arguments inside an arrow

An arrow has no arguments object, so the name either reaches the outer function's arguments or throws a ReferenceError. For a variable number of inputs, use a rest parameter: (...values) => ....

Mini challenge

A shopping-cart report built with arrows

Write code that prints a report for the items in a shopping cart. Write the helpers as arrows, write the methods that need this with method syntax, and use arrow callbacks inside those methods so they can read this.currency.

  • Write withTax(price, rate) as a concise arrow with a default rate of 0.1
  • toLine(item) returns an object { label, total } (remember the parentheses)
  • cart.total() adds up every item with reduce and an arrow callback
  • cart.print() logs one line per item from an arrow callback inside forEach, using this.currency
cart-report.js
// TODO: concise arrow with a default rate of 0.1, rounded to 2 decimals
const withTax = undefined;

// TODO: arrow that returns { label: NAME IN CAPITALS, total: withTax(price * qty) }
const toLine = undefined;

const cart = {
  currency: "USD",
  items: [
    { name: "notebook", price: 4, qty: 3 },
    { name: "pen", price: 1.5, qty: 4 },
  ],
  total() {
    // TODO: reduce over this.items with an arrow callback
  },
  print() {
    // TODO: forEach with an arrow callback; read this.currency inside it
  },
};

cart.print();
console.log(`TOTAL ${cart.total()} ${cart.currency}`);

Expected: Two lines, NOTEBOOK: 13.2 USD and PEN: 6.6 USD, followed by TOTAL 19.8 USD.

Show hint

Round to two decimals with Math.round(value * 100) / 100. Do not write print() itself as an arrow: then this would no longer be cart.

Show solution
cart-report.js
const withTax = (price, rate = 0.1) => Math.round(price * (1 + rate) * 100) / 100;

const toLine = (item) => ({
  label: item.name.toUpperCase(),
  total: withTax(item.price * item.qty),
});

const cart = {
  currency: "USD",
  items: [
    { name: "notebook", price: 4, qty: 3 },
    { name: "pen", price: 1.5, qty: 4 },
  ],
  total() {
    const sum = this.items.reduce((acc, item) => acc + toLine(item).total, 0);
    return Math.round(sum * 100) / 100;
  },
  print() {
    this.items.forEach((item) => {
      const line = toLine(item);
      console.log(`${line.label}: ${line.total} ${this.currency}`);
    });
  },
};

cart.print();
console.log(`TOTAL ${cart.total()} ${cart.currency}`);

Quick quiz 1 / 3

What does const double = (x) => { x * 2 }; console.log(double(4)); print?

Quick quiz 2 / 3

In const user = { name: "Ana", hi: () => this.name };, why does user.hi() not return "Ana"?

Quick quiz 3 / 3

What happens when you run const Person = (name) => { this.name = name; }; new Person("Ana");?

What to remember

  • An arrow function is a short function expression: (params) => expression
  • A single expression returns automatically; with braces you must write return
  • Wrap a returned object literal in parentheses: ({ ... })
  • Arrows take this and arguments from where they are written, which suits callbacks inside methods
  • Use regular functions or method syntax for object methods, constructors and anything that needs its own this

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Arrow Functions | Thuta Learning