← Back to JavaScript series
🏹
Functional Β· ES6
Intermediate Β· Prerequisite: 09_Destructuring_and_Spread

10. Arrow Functions

If the body spans multiple lines, you need explicit braces and a `return`.

arrow functionthisconcise syntax
Duration
⏱ ~1 hour
Level
πŸ“Š Intermediate
Prerequisite
🎯 Lecture 9
OUTCOME
If the body spans multiple lines, you need explicit braces and a `return`.

What you'll learn

  • 1Know arrow function syntax.
  • 2Use implicit return for one-line bodies.
  • 3Explain the `this` difference between `function` and arrow functions.
  • 4Use arrow functions naturally as callbacks.
  • 5Know when an arrow function is the wrong tool (methods, constructors).

Overview

If the body spans multiple lines, you need explicit braces and a `return`.

Core Concepts

1. Basic syntax

javascript
const add = (a, b) => a + b;
const square = x => x * x;          // parens optional for a single parameter
const log = () => console.log("hi"); // no arguments β†’ empty parens

If the body spans multiple lines, you need explicit braces and a `return`.

javascript
const greet = (name) => {
  const msg = `Hi, ${name}`;
  return msg;
};

2. Implicit object return

An object literal looks like a function body block, so you have to wrap it in parentheses.

javascript
const make = (x, y) => ({ x, y });

3. this differences

A regular `function`'s `this` depends on how it was called. An arrow function uses the `this` of **where it was declared** (lexical this).

javascript
const obj = {
  name: "A",
  hello1: function () { return this.name; },
  hello2: () => this?.name,
};
obj.hello1(); // "A"
obj.hello2(); // undefined (this at the time of declaration)

So object methods usually use `function` or method shorthand, while callbacks that need to keep the outer `this` use arrows.

4. Great for callbacks

javascript
[1, 2, 3].map((x) => x * 10); // [10, 20, 30]
setTimeout(() => console.log("done"), 100);

Examples

FileWhat it covers
`01_basic.js`Basic syntax and parameter forms
`02_implicit_return.js`Implicit return and returning objects
`03_this_diff.js`Comparing this behavior
`04_callbacks.js`Array method callbacks

src/01_basic.js

javascript
/**
 * Basic arrow function syntax
 */
"use strict";

const add = (a, b) => a + b;
const square = (x) => x * x;
const noArg = () => 42;

console.log(add(2, 3));
console.log(square(5));
console.log(noArg());

const greet = (name) => {
  const msg = `Hi, ${name}`;
  return msg;
};
console.log(greet("Sun"));

src/02_implicit_return.js

javascript
/**
 * Implicit return and returning objects
 */
"use strict";

const double = (x) => x * 2;
console.log(double(7));

// Returning an object requires parens
const point = (x, y) => ({ x, y });
console.log(point(1, 2));

// Wrong (interpreted as a block)
const wrong = (x, y) => { x, y };
console.log("wrong =", wrong(1, 2)); // undefined

src/03_this_diff.js

javascript
/**
 * this differences
 */
"use strict";

const obj = {
  name: "ObjA",
  fn() {
    return this.name;
  },
  arrow: () => {
    // lexical this = module/global
    return typeof this === "undefined" ? "undefined" : "global";
  },
};

console.log("fn =", obj.fn());
console.log("arrow =", obj.arrow());

// Arrow functions are useful when a callback needs to keep the outer this
const timer = {
  seconds: 0,
  start() {
    const tick = () => {
      this.seconds += 1;
    };
    tick();
    tick();
    return this.seconds;
  },
};
console.log("timer =", timer.start()); // 2

src/04_callbacks.js

javascript
/**
 * Arrow functions as array callbacks
 */
"use strict";

const nums = [1, 2, 3, 4, 5];

console.log(nums.map((x) => x * x));
console.log(nums.filter((x) => x % 2 === 0));
console.log(nums.reduce((a, b) => a + b, 0));

setTimeout(() => console.log("delayed log"), 10);

Common Mistakes

  1. Forgetting parens when returning an object β€” it gets parsed as a block and returns `undefined`.
  2. Defining an object method as an arrow and being surprised that `this` doesn't work.
  3. Forgetting that arrow functions have no `arguments` object.
  4. Trying to call an arrow function with `new` (not supported).
  5. Adding `return` to a one-line arrow expression β€” SyntaxError.

FAQ

Q1. Can I use arrow functions everywhere?

Methods and prototype definitions are usually better with `function`.

Q2. What if I need `arguments`?

Use rest parameters (`...args`).

Q3. How are arrows different from anonymous functions?

Arrows are also anonymous; assigning them to a variable gives them a name. The `name` property is inferred from the variable.

Practice

  • `homework_01.js` β€” Convert `function` declarations into arrow functions.
  • `homework_02.js` β€” Write an arrow function point factory that returns an object.

homework/README.md

## homework_01.js β€” Convert the following functions to arrow form.

javascript
function add(a, b) { return a + b; }
function isEven(n) { return n % 2 === 0; }
function shout(msg) { return msg.toUpperCase() + "!"; }

## homework_02.js β€” Write `makePoint(x, y)` as an arrow function returning `{ x, y, distance }`, where `distance` is the distance from the origin.

homework/answer/homework_01.js

javascript
/**
 * Homework 1: convert to arrow
 */
"use strict";

const add = (a, b) => a + b;
const isEven = (n) => n % 2 === 0;
const shout = (msg) => msg.toUpperCase() + "!";

console.log(add(2, 3));
console.log(isEven(4));
console.log(shout("hello"));

homework/answer/homework_02.js

javascript
/**
 * Homework 2: point factory
 */
"use strict";

const makePoint = (x, y) => ({
  x,
  y,
  distance: Math.hypot(x, y),
});

console.log(makePoint(3, 4)); // { x:3, y:4, distance:5 }

Next Lecture

[11_Array_Higher_Order_Functions](../11_λ°°μ—΄_κ³ μ°¨ν•¨μˆ˜/) β€” map/filter/reduce.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—