DEV Community

Matthew Foley
Matthew Foley

Posted on

3 1

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)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay