Why is undefined not equal to zero in JavaScript?

I find the likelihood of comparing JavaScript. I wanted to find an example of how complicated comparisons are and how errors can occur in some situations.

I thought about where some input variable remains undefined, and compares to zero. Since undefined is false when converting to Boolean, and zero is false when converting to Boolean, I decided to check the following code:

var x;
//Here x should be initialized but due to some circumstances is not
if(x == 0){
   //This should run
}

Amazing ...

Boolean(undefined) //false
Boolean(0) //false
x //undefined
x == 0 //false

Why is this so?

+4
source share
3 answers

This behavior is specified in the specification. Abstract equality comparison algorithm.

From specification

x == y, x y - , true false. :

  • Type(x) Type(y), ... ...

  • x null, y - undefined, true.

  • x - undefined y - null, true.
  • Type(x) - Number Type(y) - String, comparison x == ToNumber(y).
  • Type(x) - , Type(y) - Number, ToNumber(x) == y.
  • Type(x) , ToNumber(x) == y.
  • Type(y) , x == ToNumber(y).
  • Type(x) , , Type(y) , comparison x == ToPrimitive(y).
  • Type(x) - Object, Type(y) - String, Number, ToPrimitive(x) == y.
  • false.

undefined (0) , , , , undefined.
, null, true, , 10., "return false".

+6
Boolean(undefined) //false
Boolean(0) //false

Boolean false , 0, null, undefined, "" ( ) ..

, undefined == 0

0

This is not deep. If you want to compare value and type, you can use triple '='

if(x === 0){
    //This should run
}

Otherwise, undefined == null, etc.

-6
source

Source: https://habr.com/ru/post/1660825/


All Articles