CodeBlanks Logo Icon CodeBlanks

Arrow function syntax

JavaScript course · Intermediate · Lesson 1/134

Learn the => shorthand for functions and how it differs from a classic function.

Arrow function syntax

An arrow function is a shorter way to write a function expression. The => arrow separates parameters from the body.

Classic form:

const square = function(n) {
  return n * n;
};

Arrow form:

const square = (n) => n * n;

In a single-line body you do not write return; the value comes back automatically. This is called implicit return.

Arrows as callbacks

Arrow functions shine as callbacks. They pair well with map and filter from the basics.

Classic:

const nums = [1, 2, 3];
const doubled = nums.map(function(n) {
  return n * 2;
});

With an arrow:

const doubled = nums.map((n) => n * 2);

The arrow shrinks the callback to one line and improves readability.

Exercise Convert the classic function to an arrow

Convert the square function below into an arrow function. It should return the square of n with a single-line (implicit return) body.

Show example solution
const square = (n) => n * n;

Test yourself

  1. Which is a valid arrow function?

    • const f = function() => 5;
    • const f = () => 5;
    • const f = () -> 5;
    • const f = => 5;
    Show answer

    const f = () => 5; — Correct. Zero parameters use empty parentheses <code>()</code> then <code>=></code>.

  2. Complete the blank with the arrow

    const double = (n) ____ n * 2;
    Show answer
    const double = (n) => n * 2;
  3. What does the call below return?

    const area = (w, h) => w * h;
    area(3, 4);
    • 12
    • 7
    • 34
    • undefined
    Show answer

    12 — Correct. 3 * 4 = 12; implicit return sends the value back.

All lessons in Intermediate