Does Javascript Use Optimization In Boolean Expressions?
Solution 1:
Yes, it's normal. It's called a short-circuit evaluation and is both handy and very common (i.e. is present in a lot of languages (C, C++, Java, Perl, many others), not just JavaScript).
Solution 2:
That is the way it should be!
Quote from wikipedia : the logical conjunction (a.k.a. &&
) "results in true if both of its operands are true, otherwise the value of false."
In other words, if the first operand is false, there is no need to proceed with the evaluation of the second one because the result will always be false.
So an expression like
if(condition1 && condition2)
is equivalent to
if(condition1){
if(condition2){
}
}
So you see that if the first condition is false, there is no need to continue evaluating your expression, because the answer will be unchanged.
Solution 3:
If you want to explicitly run both functions, you can choose to only run &&
when both have been evaluated:
var l = loginCheck(), // will evaluate
p = passwordCheck(); // will evaluatereturn l && p; // if l failed, p will be ignored, but both functions// have been evaluated anyway
Post a Comment for "Does Javascript Use Optimization In Boolean Expressions?"