liveBook · Manning

Default parameter

As explained in JavaScript in Depth

A function parameter that receives a specified default expression value when the corresponding argument is omitted or undefined.

A default parameter can make a function behave as though its body had an extra scope. JavaScript evaluates default expressions in an intermediate parameter scope between the outer scope and the function body. section 6.4

The scope rules explain several non-obvious results:

  • A default expression resolves names from the outer scope, not from declarations inside the function body. section 6.4
  • Earlier parameters are visible to later default expressions, so b = a can reference a. section 6.4
  • A body declaration can shadow a parameter without changing the value captured by a function created in the parameter scope. section 6.4
const x = 'outer';
function example(a = x, b = a) {
  const x = 'inner';
  console.log(a, b);
}
example();  // 'outer', 'outer'

Compare outer-scope lookup with a same-named declaration inside the function body. section 6.4

function strange(a = () => b, b = 1) {
  let b = 2;
  return a();
}
strange();  // 1, not 2!

Observe a closure capturing the parameter-scope binding rather than the body’s shadowing declaration. section 6.4

How JavaScript in Depth covers it

How deep it goes
Descends to the intermediate parameter scope and its shadowing rules, rather than stopping at default-value syntax.
Examples
Uses outer and inner x bindings, chained defaults, and a closure that captures a shadowed parameter.
What you can do after
Evaluate/understand which binding a default expression or nested function captures in JavaScript.
How it connects
Connects default parameters to closures, lexical scope, parameter binding, and variable shadowing.

Also explained in

Compare how 3 books explain default parameter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.