3

I just saw this shortcut being used in some JavaScript.

(9 + 2) / 2|0; // results in 5 

When you do the normal math it results in 5.5.

How come the top expression is resulting in Math.floor((9+2)/2)? Can someone point in in the direction of what that pipe is doing, I don't understand the shortcut.

peterh
  • 11,875
  • 18
  • 85
  • 108
trebek1
  • 755
  • 1
  • 8
  • 28

2 Answers2

3
  1. Firstly the result of (9+2)/2 is 5.5 in JavaScript
  2. Then it's applied a bitwise Or operation. For JavaScript, the bitwise operations don't work directly on the 64-bit representations. Instead, the value is converted into a 32-bit integer, which means 5.5 to 5, then the result of 5|0 is 5.
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47
3

A single pipe | is BitWise OR.
Bitwise operator only allow integer values, so after decimal point value is discarded.

Bitwise OR operator | takes 2 bit patterns, and perform OR operations on each pair of corresponding bits.
The following example will explain it.

1010                            
1100       
----------bitwise or
1110       
yash
  • 2,101
  • 2
  • 23
  • 32