I read that sometimes the && operator is used to “short circuit” JavaScript into believing that a return value of 0 is 0 and not NaN because 0 is a falsy number in JavaScript. I’ve been looking around to figure out what all this means. Can someone explain it to a layman?
For example:
function sign(number) {
return number && number / Math.abs(number); }
Will return 0 if number is 0.
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 like0, the empty string""andnullare “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 youNaNwhennumber = 0, but:Will give you
0instead of aNaNsince0is falsy. In a boolean contextfalse && anythingisfalse, so there’s no point in evaluating the right hand side. Similarly:Will give you
msgif the stringmsgis not empty (truthy) sincetrue || anythingistrue. Ifmsgis empty, it gives you"No message instead".