Home  >  Article  >  Web Front-end  >  Analysis of the difference between Null and Undefined in JavaScript_javascript skills

Analysis of the difference between Null and Undefined in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:52:111259browse

There are two primitive types in JavaScript: Null and Undefined. These two types often make JavaScript developers confused, when is it Null and when is it Undefined?

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

The Null type also has only one value, which is null. Null is used to represent an object that does not yet exist. It is often used to indicate that a function attempts to return a non-existent object.

Copy code The code is as follows:

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

This code displays as true, which means that the value of oVlaue is undefined because we have not initialized it.

Copy code The code is as follows:

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

When the DOM node with the id "notExistElement" does not exist on the page, this code displays "true" because we are trying to get an object that does not exist.

Copy code The code is as follows:

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

The first line of code is easy to understand, the type of undefined is Undefined; the second line of code makes people confused, why is the type of null again Object? In fact, this was a mistake in the initial implementation of JavaScript, which was later adopted by ECMAScript. Today we can explain that null is a placeholder for a non-existent object, but we still need to pay attention to this feature when actually coding.

Copy code The code is as follows:

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

ECMAScript considers undefined to be derived from null, so it defines them as equal. However, if in some cases we must distinguish between these two values, what should we do? The following two methods can be used.
Copy code The code is as follows:

alert(null === undefined); //output "false"
alert(typeof null == typeof undefined); //output "false"

Using the typeof method has been mentioned before. The types of null and undefined are different, so "false" is output. And === represents absolute equality, here null === undefined outputs false.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn