http://www.markhansen.co.nz/javascript-optional-parameters/
Import is:
function connect(hostname, port, method) {
hostname = hostname || "localhost";
port = port || 80;
method = method || "GET";
}
The short-circuit OR operator ||
returns the left side if the left argument is truthy (evaluates to true
in conditionals), otherwise it checks if the right argument is truthy, returning it. We can use this shortcut because undefined
is falsy: in conditionals, undefined
evaluates to false
.
This shortcut approach is a very common idiom, but it does have a disadvantage: You can’t use for any argument that could accept a falsy value: false
, 0
, null
, undefined
, the empty string ""
, and NaN
.
Using the ||
shortcut will override any falsy input value. If you expect a falsy value, you must explicitly check for argument === undefined
.