This is (kind of?) clever use of the tilde (~
) operator, but it just leads to confusion. The ~
(effectively) adds one to the number and flips the sign.
~0 === -1
~1 === -2
~-1 === 0
etc.
The -
flips the sign back to what it originally was.
So the end result of -~j
is j + 1
This then gets added to a[i]
and assigned to y
Moral of the story: don't ever write code like this.
Note: There are legitimate use-cases for the ~
operator, most notably in the .indexOf()
function. If you want to check if something was found in an array/string, rather than saying:
if (arr.indexOf("foo") > -1) {...}
, you can say
if (~arr.indexOf("foo")){...}
. This is because if the value is not found, indexOf()
will return -1, which, when passed through the tilde operator, will return 0, which coerces to false. All other values return 0 through n, which return -(1 through n+1) when passed through the tilde operator, which coerce to true.