3

For a while, I have used "||" as the "or" indicator. One day, I was debugging some things in a console, and I accidentally put a single | instead of two. It still worked as expected.

console.log(0||1); // 1
console.log(0|1); // 1

Is there any difference? Here, there evidently isn't, but there might be some hidden difference that I don't know about. I apologize if this is a duplicate, but I assure you I have looked for the answer beforehand.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Broken Disc
  • 35
  • 1
  • 4
  • 2
    Getting the same result for only one test case, is not an evidence or indication that they are equal. `0/1` and `0*1` also have the same result, but `*` and `/` are for sure not the same. So you should always test with more than just one combination. `2|1` is `3` and `2||1` is `2`. – t.niese Mar 31 '18 at 16:26

2 Answers2

3

That is called a bitwise OR, meaning it ORs the individual bits that compose a value based on binary rules.

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

For your example, 0 in binary is just 0000, and 1 in binary is 0001.

Thus 0|1 is:

0000 | 0001

Which, when we apply the table above between each binary digit of the two numbers:

0 or 0 = 0
0 or 0 = 0
0 or 0 = 0
0 or 1 = 1

give us 0001, which when converted to decimal becomes 1.


The way || (logical OR) behaves is using coercion rules which returns the first truthy item (or just the last item) in a sequence of ||.

Since 0 is falsy, 0 || 1, will return 1.


Just because the answers happen to be the same in these two situations, does not mean that the operations always produce equal results.

For instance:

2|3 === 3
2||3 === 2
nem035
  • 34,790
  • 6
  • 87
  • 99
0

| is a bitwise OR.

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1

|| is a logical OR.

In your example, 0|1 will evaluate to 1, because ... 0000 | ... 0001 evaluates to ... 0001.

0||1 will evaluate to 1 because 0 is falsy so it'll return the right operand 1

pushkin
  • 9,575
  • 15
  • 51
  • 95