Home » Javascript » What does the “|” (single pipe) do in JavaScript?

What does the “|” (single pipe) do in JavaScript?

Posted by: admin November 30, 2017 Leave a comment

Questions:
console.log(0.5 | 0); // 0
console.log(-1 | 0);  // -1
console.log(1 | 0);   // 1

Why does 0.5 | 0 return zero, but any integer (including negative) returns the input integer? What does the single pipe (“|”) do?

Answers:

This is a bitwise or.
Since bitwise operations only make sense on integers, 0.5 is truncated.

0 | x is x, for any x.

Questions:
Answers:

Bit comparison is so simple it’s almost incomprehensible 😉 Check out this “nybble”

   8 4 2 1
   -------
   0 1 1 0 = 6  (4 + 2)
   1 0 1 0 = 10 (8 + 2)
   =======
   1 1 1 0 = 14 (8 + 4 + 2)

Bitwise ORing 6 and 10 will give you 14:

   alert(6 | 10); // should show 14

Terribly confusing!

Questions:
Answers:

A single pipe is a bit-wise OR.

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

JavaScript truncates any non-integer numbers in bitwise operations, so its computed as 0|0, which is 0.