How do default parameters work, and when is the default value evaluated?
A parameter with a default uses that value only when the caller does not supply one. The default expression is worked out at call time, once for each call, and only when it is really needed.
function greet(name = 'friend') {
return 'Hello ' + name;
}
console.log(greet());
console.log(greet('Ada'));
console.log(greet(undefined));
console.log(greet(null));
console.log(greet(''));
// The default can depend on another parameter.
function withSuffix(value, suffix = 'px') {
return value + suffix;
}
console.log(withSuffix(10));
console.log(withSuffix(10, 'em'));The order of evaluation is left to right, and a default can refer to any parameter that was declared before it. That is the single most useful property of the feature, because it lets you build a parameter list where later values are worked out from earlier ones, without repeating the same expression inside the body of the function.
Two details are commonly misunderstood. Passing an explicit empty value does not trigger the default, because only a missing argument or an explicit empty marker does. And the default expression is not worked out at all when the caller supplies a value, so a default that calls an expensive function costs nothing on the common path.
There is one classic mistake worth mentioning. If the default refers to a parameter that comes after it, then the code is a syntax error, because the parameters are given their values in order and a later one does not exist yet at that point.