Arrow functions

Topic 2 of 6 in Functions7 min readBeginnerFree course

Overview

Arrow functions are a shorter way to write function expressions. Added in ES2015, they suit small callbacks and keep this from the code around them instead of creating their own.

JavaScript
// Function expression
const doubleFn = function (n) {
  return n * 2;
};

// Same thing as an arrow function
const double = (n) => n * 2;

They’re everywhere in modern JavaScript, especially as arguments to other functions:

JavaScript
const prices = [100, 250, 40];
const withTax = prices.map((p) => p * 1.18);
button.addEventListener('click', () => console.log('Clicked!'));

Syntax

An arrow function drops the function keyword and puts => (read “goes to” or “arrow”) between the parameter list and the body.

Four versions of the same double function. The function expression drops the function keyword to become an arrow with a body; with one expression it drops the braces and return to use an implicit return; with one parameter the parentheses become optional.

Implicit return

When the body is a single expression, leave out the braces and return — the expression’s value is returned for you.

JavaScript
const square = (x) => x * x;
const isAdult = (age) => age >= 18;
const fullName = (first, last) => `${first} ${last}`;
const toUser = (name) => ({ name, active: true });

Returning an object? Wrap it in parentheses. Without them, the braces are read as a function body and the function returns undefined.

JavaScript
const bad = (name) => { name: name };   // returns undefined!
const good = (name) => ({ name: name }); // returns the object

Block body

When you need several statements, use braces — and then you must write return yourself:

JavaScript
const describe = (score) => {
  const passed = score >= 50;
  const label = passed ? 'Pass' : 'Fail';
  return `${label} (${score})`;
};

Forgetting return inside braces is the most common arrow-function bug: the function runs but gives back undefined.

Parameters

With exactly one parameter the parentheses are optional. With none, or more than one, they’re required.

JavaScript
const shout = word => word.toUpperCase();
const greet = () => 'Hi!';
const add = (a, b) => a + b;
const withDefault = (name = 'friend') => `Hi ${name}`;
const sum = (...nums) => nums.reduce((t, n) => t + n, 0);

Many teams (and Prettier, by default) always write the parentheses, (word) => …, for consistency. This course does the same.

Line breaks

The => must be on the same line as the parameters. A long implicit-return body can go on the next line:

JavaScript
const formatPrice = (amount, currency) =>
  new Intl.NumberFormat('en-IN', { style: 'currency', currency }).format(amount);

Arrow functions as callbacks

Their short form shines when a function is passed straight into another one. Compare:

JavaScript
// Regular function expression
const evens = numbers.filter(function (n) {
  return n % 2 === 0;
});

// Arrow function
const evens = numbers.filter((n) => n % 2 === 0);

Chained array methods read almost like a sentence:

JavaScript
const names = users
  .filter((u) => u.active)
  .map((u) => u.name)
  .sort();

How this works

Regular functions get their own this, set by how they’re called. Arrow functions don’t get their own this. They use the this of the surrounding code — wherever the arrow was written — which is why they’re handy for callbacks inside methods.

JavaScript
class Timer {
  seconds = 0;
  start() {
    setInterval(() => {
      this.seconds++; // `this` is still the Timer
    }, 1000);
  }
}

With a regular function, the callback would get its own this (not the Timer) and this.seconds++ would fail. Before arrow functions, people wrote const self = this; or used .bind(this) to work around it. You’ll learn the full rules in Methods and this.

When not to use them

  • Object methods that need this to be the object. An arrow function would borrow this from outside the object:

    JavaScript
    const counter = {
      count: 0,
      increment: () => { this.count++; }, // ✗ this is not counter
      add() { this.count++; },            // ✓ method shorthand
    };
  • Constructors — arrow functions can’t be called with new.

  • Functions that read the arguments object — arrow functions don’t have one; use rest parameters (...args) instead.

  • DOM event handlers that rely on this being the element. Use event.currentTarget instead, or a regular function.

  • Functions you want hoisted. Arrow functions are stored in variables, so they only exist after the line that defines them.

Quick comparison

Function declaration Arrow function
Syntax function f(x) { return x; } const f = (x) => x;
Hoisted Yes No
Own this Yes, depends on the call No, uses surrounding this
arguments object Yes No
Can use new Yes No
Best for Named, top-level functions; methods Callbacks, small helpers
Exercise

Rewrite them as arrow functions

Turn each function into an arrow function, using an implicit return where you can.

JavaScript
function isEven(n) {
  return n % 2 === 0;
}

function makeUser(name) {
  return { name: name, active: true };
}

Summary

  • (params) => expression returns the expression automatically.
  • Use braces and return when the body needs more than one statement.
  • Wrap an object literal in parentheses to return it implicitly.
  • Arrow functions borrow this from where they’re written and have no arguments.
  • Use them for callbacks and small helpers; use regular functions for object methods and constructors.