Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Default parameter syntax

Use `parameter = expression` in a function definition to supply a value when the corresponding argument is omitted or explicitly passed as `undefined`.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

function f(a, b = a) { /* ... */ }
const g = (a, b = a) => b;
function h({ x = 1 } = {}) { return x; }

Default parameter syntax puts parameter = expression in the parameter list of a function, method, or arrow function. The default applies only when the argument at that position is omitted or is undefined. Values such as null, false, 0, and "" pass through unchanged. To use an earlier default while supplying a later argument, pass undefined in the earlier position.

Parameters are initialized from left to right before the function body runs. An initializer is evaluated on each call that needs it, so items = [] creates a fresh array each time that default is used. An initializer can read an earlier parameter, but reading a later parameter before it is initialized throws ReferenceError. Declarations in the function body are not visible to parameter initializers.

In function h({ x = 1 } = {}) { return x; }, the outer = {} handles an omitted or undefined argument; the inner x = 1 handles a missing or undefined property. Calling h(null) throws TypeError: the outer default does not replace null, and null cannot be destructured.

A parameter without a default can follow one with a default, but it does not count toward the function’s length. That property counts only parameters before the first initializer for a whole parameter and always excludes the rest parameter. A rest parameter cannot have an initializer.

Examples

{
  function collect(value, label = value, items = []) {
    items.push(label);
    return items;
  }

  console.log(JSON.stringify(collect("A")));
  console.log(JSON.stringify(collect("B", undefined)));
  console.log(JSON.stringify(collect("C", null)));
  console.log(JSON.stringify(collect("D", false, ["start"])));
  console.log(String(collect.length));
}

Result

["A"]
["B"]
[null]
["start",false]
1

Omitting `label` or passing `undefined` uses `value`, but `null` and `false` are preserved. The first three calls create separate arrays; the fourth appends to the supplied array. `collect.length` is `1` because only `value` counts.

Related lessons

  • JavaScript · Lesson 21 · Advanced · Version: 4
  • JavaScript · Lesson 27 · Advanced · Version: 4
  • JavaScript · Lesson 29 · Advanced · Version: 4
  • JavaScript · Lesson 44 · Advanced · Version: 4
  • JavaScript · Lesson 45 · Advanced · Version: 4

Sources