How does x|0 floor the number in JavaScript?

Because, according to the ECMAScript specifications, bitwise operators operators call ToInt32 on each expression to be evaluated.

See 11.10 Binary Bitwise Operators:

The production A : A @B, where @ is one of the bitwise operators in
the productions above, is evaluated as follows:

  1. Evaluate A.

  2. Call GetValue(Result(1)).

  3. Evaluate B.

  4. Call GetValue(Result(3)).

  5. Call ToInt32(Result(2)).

  6. Call ToInt32(Result(4)).

  7. Apply the bitwise operator @ to Result(5) and Result(6). The result is a signed 32 bit integer.

  8. Return Result(7).

Leave a Comment