-1

I was checking something on my browser console and accidentally used | instead of || ( OR ).

What is functionality of this operator ? i did some google search but nothing comes to relevant.

2 | 4
6
1 | 2
3
4 | 5
5
8|10
10
8 | 10
10
10 | 8
10
2 || 4
2
user2864740
  • 54,112
  • 10
  • 112
  • 187
Red
  • 5,488
  • 11
  • 60
  • 111
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators – elclanrs Feb 22 '14 at 09:11
  • Related: http://stackoverflow.com/questions/5690512/whats-the-difference-between-and-in-javascript , http://stackoverflow.com/questions/7051811/what-does-the-operator-do?lq=1 , http://stackoverflow.com/questions/6194950/what-does-the-single-pipe-do-in-javascript?lq=1 – user2864740 Feb 22 '14 at 09:19

5 Answers5

3

It is bitwise or. It checks each bit one by one in the two operands the output bit is set ( 1 ) if one of the two bits is set.

Ex: var test = 5 | 3

5 -> 101 ( leading zeros are neglected here)

3 -> 011

then test will be 7 (111)

Chethan N
  • 1,064
  • 1
  • 10
  • 23
0

| (Bitwise OR)

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table for the OR operation is:

a   b   a OR b
0   0   0
0   1   1
1   0   1
1   1   1


     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   -------------------------------- 
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)

Bitwise ORing any number x with 0 yields x.

Bitwise ORing any number x with -1 yields -1.

Source MDN

Adrian Enriquez
  • 7,236
  • 7
  • 39
  • 62
0

Binary OR

0 OR 0 -> 0

0 OR 1 -> 1

1 OR 0 -> 1

1 OR 1 -> 1

(Easy to remember - 0 OR 0 gives 0. Any other cases gives 1)

If you have e.g. 4 | 1 -> 4 in binary form is 100 and 1 is 001. Then 100 | 001 -> 101 (or 5 in decimal)

Also the logical OR (||) simply treats your left and right values and 1 and 0 and works the same as above.

0

The | is a bitwise OR instead of boolean OR ||

That means it will do OR on every bit like 2 is binary 10 and 4 is binary 100, results in 110.

If you calculate all your results above in binary numbers you will see.

This is useful for bitmasks or evaluating flags. If you program nearer to hardware you will often find this when setting register bits Or when parsing protocol data while communicating.

if (myVar | 0x2 > 0) {
  // Bit two is set!
}

Of course there are other uses too.

There is also a bitwise AND & working the same way but ands the bits.

Marcel Blanck
  • 783
  • 6
  • 11
-1

While || is a boolean logical or | is a bitwise or.

4 I 5 = 100 | 101 = 101 = 5
wumpz
  • 6,147
  • 2
  • 25
  • 25