Given this snippet of JavaScript...
var a;
var b = null;
var c = undefined;
var d = 4;
var e = \'five\';
var f = a || b || c || d || e;
alert(f); // 4
There isn't any magic to it. Boolean expressions like a || b || c || d
are lazily evaluated. Interpeter looks for the value of a
, it's undefined so it's false so it moves on, then it sees b
which is null, which still gives false result so it moves on, then it sees c
- same story. Finally it sees d
and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.
This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).