DEV Community 👩‍💻👨‍💻

Matthew Foley
Matthew Foley

Posted on

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!

Top comments (0)

🌚 Life is too short to browse without dark mode