liveBook · Manning

Default parameter

As explained in Secrets of the JavaScript Ninja, Third Edition

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

A default parameter gives a function a fallback when its matching argument is omitted or undefined, so callers need not repeat routine options. Supplying an argument overrides the fallback; an explicit null can be handled as a separate value. section 5.4.2 section 5.5.1

Assign the fallback in the parameter list, as in action = "skulking". Defaults may be simple or complex values; they are evaluated on each call, from left to right, and later defaults can refer to earlier parameters. Keep such expressions simple when readability matters. section 5.4.2

Default action

performAction("Fuma") returns "Fuma skulking", while performAction("Yagyu", "sneaking") returns "Yagyu sneaking". section 5.4.2

In TypeScript, a default can provide the inferred parameter type. Add an explicit type when the parameter should also accept values such as null. section 5.5.1

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

Runnable assertions show omitted arguments using the fallback and a supplied argument overriding it. section 5.4.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains assignment syntax, overrides, evaluation order, and references to earlier parameters; cautions against complex defaults.
Examples
Uses a ninja action default and an overridden action to demonstrate fallback behavior.
What you can do after
Apply JavaScript parameter syntax to provide fallbacks while allowing callers to override them.
How it connects
Links function parameters and arguments with TypeScript parameter types.

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 Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.