liveBook · Manning

Default parameter

As explained in Secrets of the JavaScript Ninja, Second Edition

A function parameter with a default value used when the caller omits an argument or passes undefined.

When most callers use the same argument, repeating it gets old. A default parameter puts that fallback directly in the function definition; callers can still supply a different value. section 3.4.2

Listing 3.9. Tackling default parameters in ES6
  function performAction(ninja, action = "skulking"){              #A
     return ninja + " " + action;
  }

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

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

The action defaults to "skulking" when omitted, while Yagyu can pass "sneaking" instead. section 3.4.2

Before ES6, the same pattern required checking whether the argument was undefined and assigning a fallback manually. Default parameters make that common check part of the function signature. They also suit configurable features, such as a slider whose users may accept the supplied settings. section 3.4.2

A parameter with no matching argument is undefined; default parameters provide a value when no value is supplied. Parameters are names in the function definition, while arguments are values passed when calling it. section 3.4 section 3.5

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains parameter syntax and contrasts it with a manual undefined check, without exploring runtime internals.
Examples
Uses configurable slider settings and a ninja action that defaults to skulking but can be set to sneaking.
What it assumes
Assumes familiarity with function calls, parameters, arguments, and undefined.
What you can do after
Apply ES6 default parameter syntax to define fallback values while allowing callers to pass alternatives.
How it connects
Connects function parameters and arguments with undefined and function overloading.

Related concepts

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