Home › Learn › JavaScript › Functions in depth

Arrow functions

Lesson 31 of 40. The short function syntax, and when it differs.

(a, b) => a + b is a function. With one parameter the parentheses are optional, x => x * 2; with a block body you need braces and an explicit return, (x) => { const y = x * 2; return y; }. To return an object literal directly, wrap it in parentheses: (x) => ({ value: x }).

Arrow functions are expressions, so they can be stored in variables, passed to map and sort, and returned from other functions. They differ from function in one way that matters later: they do not have their own this, which is exactly what you want inside callbacks.

const square = (x) => x * x;
const pair = (a, b) => ({ a, b });
console.log(square(4), pair(1, 2));   // 16 { a: 1, b: 2 }

Your task

Rewrite the three functions in the starter as arrow functions stored in const variables with the same names: double(n), isEmpty(text) (true for an empty or whitespace-only string), and makePoint(x, y) returning { x, y }.

Hint 1

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

Hint 2

Returning an object needs parentheses: const makePoint = (x, y) => ({ x, y });

Show the solution
const double = (n) => n * 2;
const isEmpty = (text) => text.trim() === "";
const makePoint = (x, y) => ({ x, y });

    Runs in an isolated web worker in this tab; nothing is sent anywhere.