If the left hand side is falsy (such as undefined
, which a function argument is if it is not passed), it evaluates the right hand side. The last side to evaluate is returned in JavaScript, unlike some languages which return true or false. This is handy and why this construct is used.
It exploits short circuit evaluation.
The main reason it is used is to provide a sensible default if a parameter to a function is not passed.
var a = function(b) {
b = b || [];
}
In the previous code example, if b
was not passed, it is defaulted to a blank array ([]
). However, if I passed 0
or something else falsy, it would become a blank array too. Be careful with this.