liveBook · Manning

Default value

As explained in The Joy of JavaScript

A function parameter that takes a predefined value when no argument is supplied.

A default value lets a function parameter receive a predefined value when the caller supplies no argument. JavaScript added default argument syntax with ECMAScript 2015, alongside other major language features that replaced large, infrequent releases with yearly evolution. section 1.1

In functional code, defaults can make initial state explicit without separate setup or variable reassignment. They are especially useful when a recursive function carries state through parameters. section 4.3.2

Initializing recursive state

The first call to computeCipher(data) starts with i = 0 and hash = 0. Recursive calls then provide updated values explicitly, while the defaults preserve the intended initial state. section 4.3.2

Listing 4.7 Refactoring computeCipher as a recursive function
function computeCipher(data, i = 0, hash = 0) {
  if(i >= data.length) {
    return hash ** 2;
  }
  return computeCipher(         #1
    data,
    i + 1,
    ((hash << 5) - hash + data.charCodeAt(i)) << 0
    );
}

Inspect the recursive computeCipher implementation to see default parameters establish initial state before each recursive call advances the computation. section 4.3.2

How The Joy of JavaScript covers it

How deep it goes
Explains syntax through a worked recursive example, but does not develop broader parameter-evaluation semantics.
Examples
Uses computeCipher with default i and hash parameters to initialize recursive hash computation.
What you can do after
Build it from scratch by defining recursive functions whose parameters carry explicit initial state.
How it connects
Connects default parameters with recursion, functional programming, composability, and variable reassignment.

Also explained in

Compare how 20 books explain default value →

Related concepts

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