Why is null == undefined true in javascript

If alert(null==undefined) is true .

What is the logical reason for this.

Is this something that is hard coded in javascript or there is an explanation for this.

+9
source share
4 answers

The language specification explicitly says :

If x is null and y is undefined, return true

I donโ€™t know the records about the language development process that explain the reasoning for this decision, but == has rules for processing different types, and โ€œnullโ€ and โ€œundefinedโ€ are what mean โ€œnothingโ€, therefore, if they are equal, they make intuitive sense.

(If you do not want to enter scripts, use === ).

+15
source

For the same reason that 0 == "0" - javascript is freely typed - if something can be converted to something else, then it will be if you do not use ===

 alert(null===undefined); 

Gives you a lie.

As to why these specific transformations are taking place, the answer is quite simple, "the specification says it should happen." There does not have to be a reason other than โ€œbecause it says soโ€ why a programming language behaves in a certain way.

+4
source

Using the double equality operator forces Javascript to do type coercion.

In other words, if you execute x == y , if x and y not of the same type, JavaScript will distinguish one value before comparison, for example, if you compare a string and a number, the string is always inserted into the number, and then compared

For this reason, many comparisons of mixed types in JavaScript can produce results that may be unexpected or inconsistent.

If you want to do comparisons in JavaScript, it's usually better to use the triple equality operator === rather than double. This does not lead to type coercion; instead, if the types are different, it returns false. This is most often what you need.

You should use only two times if you are absolutely sure that you need it.

+4
source

The comparison operator == does not check types. null and undefined return false . This is why your code really checks if false false .

 > null == undefined; < true > false == false < true 

However, their types are not equal.

 > typeof undefined; < "undefined" > typeof null; < "object" 

As a result, the following statement returns false, because the comparison operator === checks the types and their value.

 > undefined === null; < false 
-3
source

All Articles