DEV Community

Discussion on: Generating Random Whole numbers in JavaScript in a specific range

Collapse
 
willaiem profile image
Damian Żygadło

This is soooo confusing. I have like zero idea, why this works, espencially the "~" operator.

When I do ~(-1), I got 0, but if I do ~~(-1), I got -1. emm.... what?

Collapse
 
codingjlu profile image
codingjlu

>> and | also work in flooring a number, but in negative values it rounds "down".

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

It isn't flooring in these cases - merely removing the decimal part.

Thread Thread
 
codingjlu profile image
codingjlu

Oh, I forgot to mention—it behaves just like Math.floor unless the value is negative.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

~ is the bitwise NOT operator, which will reverse all bits in the number - having converted it to a 32-bit signed integer first. Applying it twice resets the bits to their original state. It's a dirty trick to convert to an integer

w3schools.com/js/js_bitwise.asp