In JavaScript, the boolean operators &&
and ||
don't necessarily return a boolean. Instead, they look at the "truthiness" of their arguments and might short circuit accordingly. Some values like 0
, the empty string ""
and null
are "falsy".
Short circuiting just means skip the evaluation of the right hand side of an expression because the left hand side is enough to provide the answer.
For example: an expression like var result = 100 / number;
will give you NaN
when number = 0
, but:
var result = number && 100 / number;
Will give you 0
instead of a NaN
since 0
is falsy. In a boolean context false && anything
is false
, so there's no point in evaluating the right hand side. Similarly:
// supposed msg is a potentially empty string
var message = msg || "No message";
Will give you msg
if the string msg
is not empty (truthy) since true || anything
is true
. If msg
is empty, it gives you "No message instead"
.