Explanations on what you can do with ES6 default function parameters.

Basic Usage

The most basic way to use default parameters is to set default values:

Example:

function newGame(difficulty = 'normal', numberOfPlayers = 1) {
console.log(difficulty + ', ' + numberOfPlayers + ' player' + (numberOfPlayers > 1 ? 's' : ''));
}

This function will create a new 1 player game with a default difficulty of 'normal'.

The default value will be used each time is undefined (unspecified parameters are undefined).

newGame(); // "normal, 1 player"
newGame('easy'); // "easy, 1 player"
newGame(undefined, 2); // "normal, 2 players"
newGame(undefined, undefined); // "normal, 1 player"
newGame(null, 0); // "null, 0 player"
newGame('hard', 4); // "hard, 4 players"

Computed Default Parameters

Instead of using a static value, you can derive the default value from other parameters:

In Line

An easy way to get started is by writing the formula directly in the parameter section of the function declaration.

Example:

function saveName(name, shortName = name.substring(0, 3)) {
console.log(name + ' - ' + shortName);
}

This function will use the first 3 letters of the name if the shortName parameter is not selected.

saveName('Mary'); // "Mary - Mar"
saveName('Henry', 'HNR'); // "Henry - HNR"
saveName(); // throws "TypeError: Cannot read property 'substring' of undefined

As you can see in the last example, if the first parameter is not specified, the execution blows up.

Using a function

It is also possible to use functions and variables that are available in the scope to compute the default value:

Example:

var getShortName = (n) => (n || 'AAA').substring(0, 3);

function saveName2(name, shortName = getShortName(name)) {
console.log(name + ' - ' + shortName);
}

Abstracting the parameter generation logic outside is much cleaner.

saveName2('Mary'); // "Mary - Mar"
saveName2('Henry', 'HNR'); // "Henry - HNR"
saveName2(); // "undefined - AAA"