What is this asm style “x | 0” some javascript programmers are now using?

According to JavaScript Performance for Madmen

Wrapping integer arithmetic expressions in ( ) | 0 allows the runtime to be sure that you’re doing integer arithmetic instead of floating-point arithmetic. This allows it to avoid checking for overflow and produce faster code in many cases.

and according to the page, it’s true for “most” Javascript runtimes, but doesn’t say which.

As a second source, Writing Fast JavaScript For Games & Interactive Applications states

To tell JavaScript engine we want to store integer values […] we could use bitwise or operator:

and a third source from Microsoft’s Writing efficient JavaScript page:

[…] explicitly tell the JavaScript runtime to use integer arithmetic […] use the bitwise or operator

Also, apart from in comments, none of the pages above mention asm.js, so I suspect such optimizations apply in code not explicitly marked as asm/in browsers that don’t explicitly recognize it.

Leave a Comment