Does javascript use optimization in boolean expressions?

I have a strange error when I decided to create a simple web form validation using classic javascript. There are several onblur handlers for text input fields and one "form-submit" handler.

When I use them like this:

function loginCheck() { ... return true of false } function passwordCheck() { ... } function formValidation() { return loginCheck() && passwordCheck(); } 

It does not work as I expect: "passwordCheck" was never called if loginCheck failed!

Finally, I have a workaround

 function formValidation() { ok = loginCheck(); ok &= passwordCheck(); return ok; } 

Now the password is checked. But when I choose:

 function formValidation() { ok = loginCheck(); ok = ok && passwordCheck(); return ok; } 

passwordCheck is never called again if loginCheck failed.

In addition: loginCheck and passwordCheck return boolean values, but the & = operator hides it to "0" or "1". "0" does not work for my onsubmit="return checkForm" handler. I need to convert my & = result to boolean again:

 function formValidation() { ok = loginCheck(); ok &= passwordCheck(); return ok != 0; } 

Is this normal behavior for javascript engines?

+4
javascript
Oct 22 '11 at 10:12
source share
3 answers

Yes, it is normal. It was called short circuit assessment and is both convenient and very common (i.e., present in many languages ​​(C, C ++, Java, Perl, many others), and not just JavaScript).

+7
Oct 22 '11 at 10:16
source share

It should be so!

Quote from wikipedia : logical conjunction (aka && ) "returns true if its operands are true, otherwise false."
In other words, if the first operand is false, there is no need to proceed to evaluate the second, because the result will always be false.

So an expression like

 if(condition1 && condition2) 

equivalently

 if(condition1){ if(condition2){ } } 

So you see that if the first condition is false, there is no need to continue to evaluate your expression, because the answer will be unchanged.

+2
Oct 22 '11 at 10:17
source share

If you want to explicitly run both functions, you can only choose to run && when both have been evaluated:

 var l = loginCheck(), // will evaluate p = passwordCheck(); // will evaluate return l && p; // if l failed, p will be ignored, but both functions // have been evaluated anyway 
+1
Oct 22 '11 at 10:17
source share



All Articles