Randomblue
Randomblue

Reputation: 116293

Why is ~null === -1?

A questions that stumped me on this JavaScript test was that ~null evaluates to -1.

Why does ~null evaluate to -1?

Upvotes: 2

Views: 107

Answers (2)

Rok Kralj
Rok Kralj

Reputation: 48735

First of all, ~ is a bitwise NOT operator. That means it flips all the bits in the number representation. 0010 1010 becomes 1101 0101.

As a consequence of computers using 2's complement for storing numbers, this equality holds:

~number == -number - 1

As can be shown from my previous example:

0010 1010 (this represents number 42)

1101 0101 (this represents number -43)

Now, because ~ is an operator that operates on numbers, its argument gets cast to a number first. Since null gets cast to a 0, you get -1 as a result (according the above equation).

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173572

That's because ~ is a numeric operator, so it casts null to 0 first:

> ~0
-1

It would be equivalent to this expression:

~(+null)

Likewise:

> ~[]
-1
> ~{}
-1

Upvotes: 10

Related Questions