I'm both a JavaScript / Node n0ob....but I was recently working on a project using both. I was exploring the /node_modules/ folder and I came across a particular line of code that didn't seem to immediately make sense to me. The goal is to determine if a number is odd or not.
The specific line of code is:
return !!(~~i & 1);
My question is 'Why do we need the ~~'
(related to: How to determine if a number is odd in JavaScript which shows most of the answers using % 2)
I think I understand the individual pieces.
- !! is the negation operator (twice) and will give us a true/false value from a truthy/falsey value
- ~~ is a way to truncate a value. 8.234 becomes 8.
- & is the bitwise and operator.
But I'm still questioning if we need the ~~, and if so, why?
I've been using N..toString(2) - for example:
4.0.toString(2)
> "100"
4.1.toString(2)
> "100.0001100110011001100110011001100110011001100110011"
To try and understand what the binary representations look like. In the second example, the right-most digit is a 1, but when I plug 4.1 in as the value for i, it still correctly sees that the number is even:
!!(~~4.1 & 1)
> false
!!(4.1 & 1)
> false
I've read that Javascript uses the IEEE 754 standard, and I've also read that all of the bitwise operators being used here do some implicit converting that I don't fully understand and maybe there are considerations that I'm not seeing?
Thanks