DEV Community

Discussion on: JavaScript: Double Not Operator?

Collapse
 
willsmart profile image
willsmart • Edited

The bitwise NOT operator can be used as a poor-mans integer cast. I don't know what they call it but I'm really hoping it's "squiggiggle"
~~value effectively replaces Math.trunc(Number(value) || 0)

I have to add that it's clearly a confusing hack. They're both hacks. If you want a boolean from a value, please use Boolean(value). Do it for your readers.

Squiggiggle essentially casts its input to a 32-bit signed integer (truncating decimals toward 0), or 0 if there was no reasonable integer to choose...

> ~~0
< 0
> ~~false
< 0
> ~~true
< 1
> ~~10101
< 10101
> ~~"100"
< 100

Decimals...

> ~~1.1
< 1
> ~~1.9999
< 1
> ~~ -1.9999
< -1
> ~~ -1.1
< -1
// Integer zeros don't have signs, so sqiggiggle flattens -0 down to 0:
> ~~ -0
< 0

Non-numbers work as you might expect...

> ~~"Fred"
< 0
> ~~{}
< 0
> ~~[]
< 0
> ~~null
< 0
> ~~undefined
< 0
> ~~NaN
< 0
> ~~Symbol()
< VM699:1 Uncaught TypeError: Cannot convert a Symbol value to a number

But be careful if you're passing in large numbers, as they will be clipped to a 32 bit signed integer.

> ~~(2**29)
< 536870912
> ~~(2**30)
< 1073741824
> ~~(2**31)
< -2147483648
> ~~(2**32)
< 0

-~number is a fun one to play with too, a bit useless but a good exercise in 2's complement for any teachers out there.

-~ -2
-1
-~ -1
-0
-~0
1
-~1
2