2

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

Rob P.
  • 14,921
  • 14
  • 73
  • 109

1 Answers1

1

The double ~~ is used to convert a string to an number, just like !! is used to convert a truthy/falsey value to a boolean.

var a = "4";
console.log(typeof a + " " + a); //string
console.log(typeof ~a + " " + a); //converts to number, but you get (a - 1)
console.log(typeof ~~a + " " + a);  // reverses the previous operation, keeping the number type

Now, as you realized, it's not necessary in this operations because in Javascript, when you do bitwise operations on strings they're first converted to numbers, so the double tilde becomes superfluous.

What I suspect was the intention of the maker of that snippet is that you can't really classify a decimal number as odd or even, so he just cast it as a number to get rid of the decimals, which ~~ does.

ishegg
  • 9,685
  • 3
  • 16
  • 31
  • That's a good point that I completely missed.... Odd and even don't apply to non-whole numbers. – Rob P. Sep 16 '17 at 03:45