Does JavaScript Have Non-shortcircuiting Boolean Operators?
Solution 1:
Nope, JavaScript is not like Java and the only logical operators are the short-circuited
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Logical_Operators
Maybe this could help you:
http://cdmckay.org/blog/2010/09/09/eager-boolean-operators-in-javascript/
| a | b | a && b | a * b | a || b | a + b |
|-------|-------|--------|-----------|--------|-----------|
| false | false | false | 0 | false | 0 |
| false | true | false | 0 | true | 1 |
| true | false | false | 0 | true | 1 |
| true | true | true | 1 | true | 2 |
| a | b | a && b | !!(a * b) | a || b | !!(a + b) |
|-------|-------|--------|-----------|--------|-----------|
| false | false | false | false | false | false |
| false | true | false | false | true | true |
| true | false | false | false | true | true |
| true | true | true | true | true | true |
Basically (a && b)
is short-circuiting while !!(a + b)
is not and they produce the same value.
Solution 2:
You could use bit-wise OR as long as your functions return boolean values (or would that really matter?):
if (f1() | f2()) {
//...
}
I played with this here: http://jsfiddle.net/sadkinson/E9eWD/1/
Solution 3:
JavaScript DOES have single pipe (|
, bitwise OR) and single ampersand operators (&
, bitwise AND) that are non-short circuiting, but again they are bitwise, not logical.
Solution 4:
If you need f2() to run regardless of whether or not f1() is true or false, you should simply be calling it, returning a boolean variable, and using that in your conditional. That is, use: if (f1() || f2IsTrue)
Otherwise, use single bar or single ampersand as suggested by GregC.
Post a Comment for "Does JavaScript Have Non-shortcircuiting Boolean Operators?"