This article mainly introduces the difference between null and undefined in JavaScript, this article gives a number of code examples to explain the difference between them, the need for friends can refer to the
There are two original types in javascript: null and undefined. These two types often make JavaScript developers wonder when they are null and when are undefined?
The undefined type has only one value, that is, undefined. The default value for a variable is undefined when the declared variable has not yet been initialized.
A null type also has only one value, that is, null. Null is used to represent an object that does not exist, and is commonly used to represent a function attempt to return an object that does not exist.
The code is as follows:
var Ovalue;
Alert (Ovalue = = undefined); Output "true"
This code appears to be true, representing the value of Ovlaue as undefined, because we did not initialize it.
The code is as follows:
Alert (Null = = document.getElementById (' notexistelement '));
When a DOM node with ID "notexistelement" does not exist on the page, this code appears "true" because we are trying to get an object that does not exist.
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 undefined type is undefined, and the second line of code is confusing, why is the type of null and object? In fact, this is the first implementation of JavaScript is a mistake, and later used by ECMAScript. As we can explain today, NULL is a placeholder for an object that does not exist, but you should pay attention to this feature when you actually encode it.
The code is as follows:
Alert (Null = = undefined); Output "true"
ECMAScript that undefined are derived from null, so they are defined as equal. However, if in some cases we must distinguish between these two values, what should we do? The following two methods are available.
The code is as follows:
alert (null = n = undefined); Output "false"
alert (typeof null = = typeof undefined); Output "false"
Using the TypeOf method, the null is not the same as the undefined type, so the output is "false". and = = = = Absolute equals, here null = = undefined output false.