Some common operations can be made shorter using bitwise operators. Here are some of my favorites.
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()]
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) { ... }