I’m looking at some Javascript code that is:
if ( a>2 | b>4 ) { ... }
(ignore the … above). What’s the | doing? I assume it’s logical OR, but all the references I could find online speak about ||, and I can’t find anything mentioning just |. Thanks in advance
The difference between
||and|is already explained in the other answers.However, in the above code,
|has the same effect as||due to type conversion.trueandfalseare mapped to1and0and we haveThe same goes into the other direction,
1evaluates totrueand0tofalse.So in this example,
will have the same result as
Note: This really only works with the two values
0and1.This could be some kind of micro-optimization.Update:
However, a short test reveals that using the bitwise OR for this purpose is way slower (at least in Chrome 9):
http://jsperf.com/js-or-test
Conclusion: Don’t use it instead of logical OR 🙂 Mostly likely someone forgot the second
|and is just lucky that the code produces the same result.Use boolean operators for boolean operations and bitwise operators for fancy bit masking. This might be worth reading: MDC – Bitwise Operators.