This is useful to setting default values to function arguments, e.g.:
function test (options) {
options = options || {};
}
If you call test
without arguments, options
will be initialized with an empty object.
The Logical OR ||
operator will return its second operand if the first one is falsy.
Falsy values are: 0
, null
, undefined
, the empty string (""
), NaN
, and of course false
.
ES6 UPDATE: Now, we have real default parameter values in the language since ES6.
function test (options = {}) {
//...
}
If you call the function with no arguments, or if it's called explicitly with the value undefined
, the options
argument will take the default value. Unlike the ||
operator example, other falsy values will not cause the use of the default value.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…