Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between Single And Double Vertical Bar (|, ||) in JavaScript? [duplicate]

Tags:

javascript

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.

like image 318
Broken Disc Avatar asked Jan 29 '26 23:01

Broken Disc


1 Answers

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
like image 180
nem035 Avatar answered Jan 31 '26 11:01

nem035