Analysis of the difference between Null and Undefined in JavaScript

  • 2020-06-22 23:46:23
  • OfStack

There are two primitive types in JavaScript :Null and Undefined. These two types often confuse JavaScript developers when Null and when Undefined?

The Undefined type has only one value, undefined. When a declared variable has not been initialized, the default value of the variable is undefined.

The Null type also has only one value, null. null is used to represent an object that does not exist, and is often used to indicate that a function attempts to return an object that does not exist.

 
var oValue; 
alert(oValue == undefined); //output "true" 

This code is shown as true, which means that the value of oVlaue is undefined because we didn't initialize it.


alert(null == document.getElementById('notExistElement')); 

When there is no DOM node on the page with id as "notExistElement", this code shows as "true" because we are trying to get a nonexistent object.


alert(typeof undefined); //output "undefined" 
alert(typeof null); //output "object" 

Line 1 is easy to understand. undefined is of type Undefined; Line 2 makes you wonder why null is of type Object again. This is actually an error in the original implementation of JavaScript, which has since been used by ECMAScript. Today we can interpret null as a placeholder for a nonexistent object, but pay attention to this feature when actually coding.

 
alert(null == undefined); //output "true" 

ECMAScript thinks that undefined is derived from null, so they are defined as equal. But what if, in the case of 1, 1 must distinguish between the two? You can use the following two methods.
 
alert(null === undefined); //output "false" 
alert(typeof null == typeof undefined); //output "false" 

Using the typeof method, as discussed earlier, null is not of the same type as undefined, so output "false". And === means absolutely equals, here null === undefined output false.


Related articles: