Today I learned

JavaScript shortcuts using bitwise operators

Some common operations can be made shorter using bitwise operators. Here are some of my favorites.

Rounding off a number

Math.floor(3.5) can be written as 3.5|0. The Bitwise OR operator will make an integer out of the number, and this construct is in fact used in asm.js to denote an integer.

list[list.length * Math.random() | 0]
// ...same as:
list[Math.floor(list.length * Math.random()]

Checking for -1

The Bitwise NOT operator will turn -1 into zero. This makes substring checks with indexOf() a little shorter.

if (~string.indexOf("John")) { ... }
// ...same as:
if (string.indexOf("John") !== -1) { ... }

You have just read JavaScript shortcuts using bitwise operators, written on March 20, 2015. This is Today I Learned, a collection of random tidbits I've learned through my day-to-day web development work. I'm Rico Sta. Cruz, @rstacruz on GitHub (and Twitter!).

← More articles