Reputation: 150829
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?
Upvotes: 0
Views: 56
Reputation: 9080
Because your second condition in if
does not execute. For &&
to work both left and right conditions should resolve to truthy value. Interpreter sees that first condition is false
, it skips second one straight away since it wasn't truthy.
Upvotes: 1
Reputation: 413826
The &&
and ||
operators have what's sometimes called short-circuit behavior, so yes, the evaluation of &&
stops as soon as an operand is false
.
Similarly, evaluation of ||
is finished as soon as an operand is true
.
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 (something != null && something.whatever == 17) {
...
}
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.
Upvotes: 5