Reputation: 1
If I do something like return a ? b : c;
or return a && a2 && a3;
Could it ever be evaluated as just return a
and then the function just returns immediately before evaluating the rest?
Upvotes: 7
Views: 2804
Reputation: 308121
To make this clearer I'm going to restate the question a little:
return a ? b() : c();
return a && a2() && a3();
In the first case, one of either b
or c
will be called but not the other.
In the second case, if a
is false then neither a2
nor a3
will be called. If a2
returns false, a3
won't be called.
Upvotes: 2
Reputation: 476970
return
is a statement, not an expression. So it can never be misinterpreted the way you think.
The statement is always of the form return [some expression];
(and the expression is optional). The expression, if present, is evaluated first, and its value is bound to the return value of the function.
Upvotes: 8
Reputation: 62063
In return a && a2 && a3;
, if a
is false, there's no need to evaluate the rest of the expression. The result will always be false. So a2
and a3
will not be evaluated. This is called "short circuiting".
Upvotes: 1