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

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

x | 0 is x, if x is an integer.

Solution 2 - Javascript

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!

Solution 3 - Javascript

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.

Solution 4 - Javascript

This example will help you.

var testPipe = function(input) { 
   console.log('input => ' + input);
   console.log('single pipe | => ' + (input | 'fallback'));
   console.log('double pipe || => ' + (input || 'fallback'));
   console.log('-------------------------');
};

testPipe();
testPipe('something'); 
testPipe(50);
testPipe(0);
testPipe(-1);
testPipe(true);
testPipe(false);

Solution 5 - Javascript

This is a Bitwsie OR (|).

The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded.

So, in our case decimal number is converted to interger 0.5 to 0.

= 0.5 | 0
= 0   | 0
= 0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatrymView Question on Stackoverflow
Solution 1 - JavascriptSLaksView Answer on Stackoverflow
Solution 2 - JavascriptTreyView Answer on Stackoverflow
Solution 3 - JavascriptYahelView Answer on Stackoverflow
Solution 4 - JavascriptNikhil MahirraoView Answer on Stackoverflow
Solution 5 - Javascriptpradip garalaView Answer on Stackoverflow