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) { |
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" |
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)) { |
This function will use the first 3 letters of the name
if the shortName
parameter is not selected.
saveName('Mary'); // "Mary - Mar" |
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); |
Abstracting the parameter generation logic outside is much cleaner.
saveName2('Mary'); // "Mary - Mar" |