Bryro
Bryro

Reputation: 243

What does -~ do in JavaScript?

I am looking at someone else's code and I am trying to figure out what they are doing. The snippet in question looks like the following:

for(j in a)     
  for(i in a)
    y=a[i]+-~j,b=a[j]

I understand the y=a[i] part, but what does +-~j do?

Upvotes: 2

Views: 2788

Answers (1)

mhodges
mhodges

Reputation: 11116

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.

Upvotes: 11

Related Questions