liveBook · Manning

Default value

As explained in Secrets of the JavaScript Ninja, Third Edition

A default value is a predefined value substituted when an expected input is not provided.

A default value is a fallback assigned to a function parameter when its argument is omitted. It can make common API calls simpler while still letting callers supply a different value. section 5.4.2

JavaScript default parameters let you:

  • Write the fallback directly in the parameter list instead of assigning it with an explicit `undefined` check. section 5.4.2
  • Use values including objects, arrays, or functions; defaults are evaluated on each call, from left to right, and later defaults can refer to earlier parameters. section 5.4.2
  • Keep defaults relatively simple: complex expressions that reference other parameters may make code harder to read. section 5.4.2
Listing 5.10 Using default parameters
function performAction(ninja, action = "skulking") {    #A
   return ninja + " " + action;
}

console.assert(performAction("Fuma") === "Fuma skulking",        #B
      "The default value is used for Fuma");             #B
                                                         #B
console.assert(performAction("Yoshi") === "Yoshi skulking",      #B
      "The default value is used for Yoshi");            #B

                                                         #B
console.assert(performAction("Hattori") === "Hattori skulking",  #B
      "The default value is used for Hattori");          #B

console.assert(performAction("Yagyu", "sneaking") === "Yagyu sneaking",  #C
         "Yagyu can do whatever he pleases, even sneak!");          #C

See omitted arguments use “skulking” while an explicitly supplied action overrides the default. section 5.4.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines parameter syntax and call-time evaluation, including left-to-right order and references to earlier parameters.
Examples
Uses a ninja-action function to demonstrate omitted arguments, overridden defaults, and a default referencing earlier parameters.
What you can do after
Apply default-parameter syntax so omitted function arguments use a fallback while callers can override it.
How it connects
Connects default parameters with function arguments, `undefined`, and API design.

Also explained in

Compare how 23 books explain default value →

Related concepts

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