What does "options = options || {}" mean in Javascript?
javascript, notation, syntax
Solution
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.
Problem
I came over a snippet of code the other day that I got curious about, but I'm not really sure what it actually does; ``` options = options || {}; ``` My thought so far; sets variable `options` to value `options` if exists, if not, set to empty object. Yes/no?