Let’s say I have the following, very simple block of code:
<script>
function hasVal(field) {
console.log(field);
var ret = false;
return ret;
}
if(hasVal('#field1') && hasVal('#field2')) {
console.log('here');
}else {
console.log('there');
}
</script>
I was expecting it to output the following:
#field1
#field2
there
What it actually outputs is:
#field1
there
Can someone please explain what’s going on here?
Does Javascript stop evaluating the rest of the if statement as soon as it gets false back from the first function call?
The
&&and||operators have what’s sometimes called short-circuit behavior, so yes, the evaluation of&&stops as soon as an operand isfalse.Similarly, evaluation of
||is finished as soon as an operand istrue.This is usually a tremendous benefit to you as a programmer, though there are rare cases (most of which bear significant code smells, like the side-effects in your example) when you do want complete evaluation. For that you can use the plain boolean
&and|, or else explicitly decompose your expression into separate statements.The reason it’s such a good thing can be seen in the extremely common case of having to check whether something is
null(or otherwise not available) before accessing a property:If the
&&were always to evaluate both sides of the expression, that idiom would not work, and our lives as software developers would be even more hellish.