2

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

Somehow, if u 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?

TeaTime
  • 474
  • 7
  • 26
  • 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 this page:

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 zeeo is essentially a way to discard the decimal part and retain the integer part.

Your other example with two is:

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

and the example with 4:

 0000 0000 0000 0000 0000 0000 0000 0101 (5)
 0000 0000 0000 0000 0000 0000 0000 0100 (4)
 --------------------------------------- ORed
 0000 0000 0000 0000 0000 0000 0000 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

Community
  • 1
  • 1
JoSSte
  • 2,210
  • 5
  • 25
  • 40