In JavaScript, can I always use boolean OR instead of conditional operator for all kind of variables (e.g. string, function, ...)?
For example z = (x || y)
They are similar, but are not quite the same. x ? x : y
ends up evaluating x
twice if x
is chosen. This could cause an unexpected effect if x
is a function call.
You can find a formal proof of this in the ECMA specification.
Another way to prove this:
function a() { c++; return true; }
function b() { d++; return true; }
var c = 0, d = 0;
a() || 3;
b() ? b() : 3;
/* c is 1; d is 2 */