This question already has an answer here:
- What does the construct x = x || y mean? 11 answers
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?
Found another variation of this:
Seems to do the same trick.
Yes. The sample is equivalent to this:
The OR operator (
||
) will short-circuit and return the first truthy value.Yes, that's exactly what it does.
This is useful to setting default values to function arguments, e.g.:
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 coursefalse
.It's the default-pattern..
What you have in your snippet is the most common way to implement the default-pattern, it will return the value of the first operand that yields a true value when converted to boolean.
the above is basically equivalent to doing the following more verbose alternative
examples of values yield by the logical OR operator:
As you can see, if no match is found the value of the last operand is yield.
When is this useful?
There are several cases, though the most popular one is to set the default value of function arguments, as in the below:
Notes
This is notably one of the differences that javascript have compared to many other popular programming languages.
The operator
||
doesn't implicitly yield a boolean value but it keeps the operand types and yield the first one that will evaluate to true in a boolean expression.Many programmers coming from languages where this isn't the case (C, C++, PHP, Python, etc, etc) find this rather confusing at first, and of course there is always the opposite; people coming from javascript (perl, etc) wonders why this feature isn't implemented elsewhere.