Javascript: What is the difference between | and ||

advertisements

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.

true and false are mapped to 1 and 0 and we have

0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1

The same goes into the other direction, 1 evaluates to true and 0 to false.

So in this example,

if ( a>2 | b>4 )

will have the same result as

if ( a>2 || b>4 )

Note: This really only works with the two values 0 and 1.


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.