||
in a variable assignment is a common way to specify a default value. This is because of JavaScript's falsy values. In JavaScript, undefined
, null
, empty string and 0
all evaluate to false
in a boolean context.
For example:
var blah = undefined;
if (blah) {
console.log('got it!');
}
else {
console.log('not true!'); // this one outputs
}
Using ||
in an assignment is a way of saying "if defined, otherwise use this".
For this code,
function values(b) {
this.b = b || 0;
}
we can use a truth table:
b this.b
------------------
5 5
10 10
0 0
undefined 0
null 0
'' 0
The values really of interest are undefined
and null
. So what we really want is:
if (b !== undefined && b !== null) {
this.b = b;
}
else {
this.b = 0;
}
But this.b = b || 0
is much shorter to write.