what does “~” operator do in this script?
As others have pointed out, it's the bitwise NOT operator. Which is all well and good, but what's it doing in this script was the question. :-)
The idea was probably to do pretty much what you said: If index
is a number, do the splice
. The first thing the ~
operator does to its operand is convert it to a number if it can. If it can't, the result is NaN
("not a number"), which is falsey, and so the condition would be false and the splice
wouldn't happen.
But the conversion doesn't result in NaN
nearly as often as I suspect the author of that code thought. :-)
Some random examples of things that won't do the splice
:
~-1 === 0
And some that will do the splice
:
~"foo" === -1
~0 === -1
~1 === -2
~2 === -3
~true === -2
~false === -1
~-2 === 1
~undefined === -1
~null === -1
~NaN === -1
Probably not ideal that it's trying to do the splice
with some of those. For instance, the true
will make it do a splice using index 1
, the false
will be index 0
.