Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "~undefined" is -1 in JavaScript? [duplicate]

Tags:

According to this post, run the following codes

> ~function () { console.log('foo');}()   foo   -1 

As we all know, the return value of the above anonymous function is undefined. Why ~undefined is -1? I couldn't find any similar question.

like image 923
zangw Avatar asked Dec 18 '15 07:12

zangw


People also ask

What causes undefined JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Why does JavaScript have both null and undefined?

The value null represents the intentional absence of any object value. It's never assigned by the runtime. Meanwhile any variable that has not been assigned a value is of type undefined . Methods, statements and functions can also return undefined .

Is undefined in JavaScript?

Undefined is also a primitive value in JavaScript. A variable or an object has an undefined value when no value is assigned before using it. So you can say that undefined means lack of value or unknown value. undefined is a token.


1 Answers

~ is bitwise NOT. It uses ToInt32 to convert the argument to a number. ToInt32 is defined as:

  1. Let number be ToNumber(argument).
  2. ReturnIfAbrupt(number).
  3. If number is NaN, +0, −0, +∞, or −∞, return +0.
    ...

In turn, ToNumber(undefined) returns NaN, so according to step 3, ToInt32 returns 0.

And ~0 is -1.

like image 50
Felix Kling Avatar answered Sep 28 '22 13:09

Felix Kling