In this instance, the ~
allows that code to turn the return value of .indexOf()
— which is a number indicating the position of the searched-for value in the array — into a boolean. In other words, it takes the "where is the value" result and turns it into a "is the value in the list" result.
How? Well, .indexOf()
returns -1
when the value is not found, and a number greater than or equal to zero if it is. The ~
operator converts its numeric argument to a 32-bit integer and then inverts every bit. That process happens to turn -1
to 0
, and any positive integer to some negative non-zero value, and 0
to -1
. When such results are subsequently examined as boolean values, the original -1
will be false
(because 0
is "falsy") while the integers greater than or equal to zero will be true
(because they're all converted to some non-zero value).