trebek1 trebek1 - 1 year ago 83
Javascript Question

Javascript pipe in math to get Math.floor without using Math.floor

Hey guys 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.

Answer Source

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.

----------bitwise or