In JavaScript, when the left hand side is considered falsy (such as when it is undefined, as is the case with a function argument that is not passed), the right hand side is evaluated. The value of the last side to be evaluated is returned, which is different from some other programming languages that return true or false. This behavior is convenient and explains why this construct is commonly used.
This behavior is made possible through the use of short circuit evaluation.
The main purpose of using this construct is to set a sensible default if a function parameter is not provided.
var a = function(b) {
b = b || [];
}
In the code example above, if the parameter b
is not passed, it is set to an empty array ([]
). However, if a value like 0
or any other falsy value is passed, it will also default to an empty array. It is important to be cautious when using this technique.