CodeBlanks Logo Icon CodeBlanks

Parameters with arrows

JavaScript course · Intermediate · Lesson 3/134

Learn single, no and multi-parameter arrow syntax.

Parameter count and parentheses

With arrows, the number of parameters changes the syntax. With a single parameter parentheses are optional: n => n + 1 or (n) => n + 1.

With no parameters parentheses are required: () => 0. With several parameters parentheses are required: (a, b) => a + b.

const inc = n => n + 1;
const zero = () => 0;
const add = (a, b) => a + b;

For consistency, many developers always use parentheses.

Default parameters

Arrow functions accept default parameters just like classic functions. When the caller omits a value, the default is used.

const greet = (name, greeting = "Hi") => `${greeting}, ${name}!`;
greet("Alex");        // "Hi, Alex!"
greet("Alex", "Hey"); // "Hey, Alex!"

A default can appear anywhere in the parameter list but usually sits at the end.

Exercise Arrow with a default parameter

Write a greet arrow function. It takes two parameters: name and greeting. Give greeting a default of "Hi". The body returns ${greeting}, ${name}! using a template literal.

Show example solution
const greet = (name, greeting = "Hi") => {
  return `${greeting}, ${name}!`;
};

Test yourself

  1. Correct syntax for a zero-parameter arrow?

    • const f = x => 0;
    • const f = [] => 0;
    • const f = => 0;
    • const f = () => 0;
    Show answer

    const f = () => 0; — Correct. With no parameters, empty parentheses <code>()</code> are required.

  2. Complete the missing part for zero parameters

    const noop = ____ => 42;
    Show answer
    const noop = () => 42;
  3. Match the parameter count

    one parameter
    n => n + 1
    zero parameters
    () => 0
    two parameters
    (a, b) => a + b
  4. What does the call return?

    const f = (a, b = 5) => a + b;
    f(3);
    • 8
    • 3
    • NaN
    • undefined
    Show answer

    8 — Correct. <code>b</code> was omitted, default 5; 3 + 5 = 8.

All lessons in Intermediate