3

Possible Duplicate:
Using bitwise OR 0 to floor a number

Performs a bitwise OR on two expressions,eg:

console.log(12.22|0) // output --->12

where does the decimal go? it's the same as parseInt function

parseInt(12.22)  // output --->12

how does it work?

Community
  • 1
  • 1
Ryan Yiada
  • 4,459
  • 4
  • 16
  • 19
  • 1
    I would guess that bitwise OR causes the double precision 12.22 to get automatically converted to an integer before applying the bitwise OR operation because you can't do a bitwise OR on a float. 12.22|1 == 13. Vote to close as a dup of http://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number. – jfriend00 Dec 07 '11 at 09:50
  • How can I close my question? I'm new here. – Ryan Yiada Dec 07 '11 at 10:01
  • You can not simply close the question. You can accept the answer by clicking the green "ok" next to the best answer. To close an answer, the community has to vote for the close. – Erik Dec 07 '11 at 10:09

1 Answers1

2

parseInt is useful in cases where one is parsing strings such as "12px".

For example:

pasrseInt("12px"); // returns 12

However, this doesn't make any sense with bit-wise OR:

"12px" | 0; // returns 0

Performing a bit-wise OR is more like applying Math.floor() to a number -- bitwise operations work on 32-bit integers in Javascript.

Peter
  • 3,701
  • 19
  • 31
  • It's like but not the same as applying `Math.floor`. It's the closer to applying `Math.trunc` although much much faster because it's not a function that could be replaced. It's an operator that can't be replaced. It's still not the same as `Math.trunc` as it will return different values for `NaN | 0` vs `Math.trunc(NaN)` – gman May 08 '17 at 04:08