Double tilde makes undefined or null to zero

September 20, 2017

~~(undefined)
//=> 0

~~(null)
//=> 0

Side note

It’s pretty useful for creating a Hashmap, since it doesn’t change an integer except changing undefined to 0.

let hash = {}

for (let item of things) hash[item] = ~~hash[item] + 1

//=> { 'a': 1, 'b': 2, ... }

Tagged withjavascript, bit manipulation

Questions, Comments, Suggestions? Open an Issue