TIL - Using ~ with Array.indexOf

mtfoley

Matthew Foley

Posted on May 31, 2020

TIL - Using ~ with Array.indexOf

I was playing with the bonjour package this morning, and when looking through the code, I noticed this function block:

function unique () {
  var set = []
  return function (obj) {
    if (~set.indexOf(obj)) return false
    set.push(obj)
    return true
  }
}
Enter fullscreen mode Exit fullscreen mode

What caught my eye was the snippet

~set.indexOf(obj)
Enter fullscreen mode Exit fullscreen mode

It seems like this function is checking for the presence of obj in the array set. I always used set.indexOf(obj) == -1 in a case like this, but this got me to look it up.

The ~ operator is bitwise not, and you can read about it on MDN. Turns out ~x evaluates to -x-1 so this will evaluate to a 0 when x = -1, and something non-zero otherwise!

Don't know if I'll use it, but the form does look nice!

💖 💪 🙅 🚩
mtfoley
Matthew Foley

Posted on May 31, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related