2

When you open up your console and type in any decimal number for example 5.123 and add | 0 after it, it will be rounded to 5.

Somehow, if you change it to | 2 , it will write down 7.

var test1 = 5.123 | 0 ; // will be 5
var test2 = 5.123 | 2 ; // will be 7
var test3 = 5.123 | 4 ; // will be 5 again

Can someone explain to my what is happening above and also, can I use this instead of parseInt?

JoSSte
  • 2,953
  • 6
  • 34
  • 54
Snackaholic
  • 590
  • 7
  • 27
  • 2
    its a bitwise operator see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators – JoSSte Sep 10 '15 at 06:33

1 Answers1

4

It's a bitwise operator... to quote MDN on Javascript operators and expressions:

Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

What happens, is that the operator treats the number as a 32 bit integer; so 5.123 is treated as:

 0000 0000 0000 0000 0000 0000 0000 0101

(the decimal part is thrown out) and 0 is treated as

 0000 0000 0000 0000 0000 0000 0000 0000

Then the OR function compares the two, and writes a 1 if either number has a 1.

So using the bitwise OR with a decimal number and zero is essentially a way to discard the decimal part and retain the integer part.

Your other example with two is (insignificant 0s have been removed):

 0101 (5)
 0010 (2)
 ---- ORed
 0111 (7)

and the example with 4:

 0101 (5)
 0100 (4)
 ---- ORed
 0101 (5)

You can use it to convert to discard the decimal part of a number - see Using bitwise OR 0 to floor a number

JoSSte
  • 2,953
  • 6
  • 34
  • 54