Explore the abyss of Null and Undefined in JavaScript

Source: Internet
Author: User
When discussing the primitive data types in Javascript, most people know the basic knowledge, from String, Number to Boolean. These primitive types are quite simple and behavior is common sense. However, this article will focus more on the unique primitive data types Null and Undefined, so what makes them so similar, but seemingly not.

Explore the abyss of Null and Undefined in javaScript

When discussing the primitive data types in Javascript, most people know the basic knowledge, from String, Number to Boolean. These primitive types are quite simple and behavior is common sense. However, this article will focus more on the unique primitive data types Null and Undefined, so what makes them so similar, but seemingly not.

Understanding Null and Undefined

In JavaScript, null is both a literal value and a keyword in the language, used to represent unrecognized object values. In other words, this is used to indicate "no value )". Although similar, undefined actually represents a non-existing value (non-existence of a value ). They are completely immutable. They do not have any attributes or methods or assign values to their attributes. In fact, attempting to access or define a property will cause a type error ). As their names imply, they are completely invalid values.

The Boolean value without a value is false, which means that they will be calculated as false in the context of the condition, such as the if statement. Use the equal operator (=) to compare the two values and other false values. They are not equal to themselves:

Null = 0; // falseundefined = ""; // falsenull = false; // falseundefined = false; // falsenull = undefined; // true

Despite this, null and undefined are not equivalent to other similarities. Each member is a unique member of its unique type. undefined is of the Undefined type and null is of the Null type. Compare the two values by using the equal-Sum Operator (=), which requires that the types and values are equal. The following demonstrates this:

Undefined === null; // false
This is an important difference and serves different purposes and reasons. To distinguish between these two values, you can think that undefined represents an unexpected value without a value, and null represents the expected value without a value.

Generate Undefined

There are many methods to generate an undefined value code. It usually encounters when trying to access a value that does not exist. In this case, in a dynamic weak language such as JavaScript, only one undefined value is returned by default, rather than an error. If no initial value is provided when a variable is declared, there will be a default value of undefined: var foo; // The default value is undefined.

When attempting to access a non-existent object attribute or array item, an undefined value is returned:

Var array = [1, 2, 3]; var foo = array. foo; // The foo attribute does not exist. The undefinedvar item = array [5] is returned. // if no index is 5 in the array, the undefined attribute is returned.

If the return statement of the function is omitted, undefined is returned:

Var value = (function () {}) (); // return undefined

The undefined parameter value is returned when the function is called:

(Function (undefined) {// The parameter is undefined })();

The void operator can also return an undefined value. Libraries like Underscore use it as a defensive type check because it is immutable and can return undefined in any context dependency:

Function isUndefined (obj) {return obj = void 0 ;}

Finally, undefined is a predefined global variable (unlike the null keyword) initialized to the undefined value:

'Undefined' in window; // true

In ECMAScript 5, this variable is read-only, not previously.

Null use case

Null is the main difference, because null is considered more useful than undefined. This is exactly why the typeof operator returns "object" when acting on a null value ". The initial reason is that, still, it is often used as an expectation to reference an empty object, just like a placeholder. This kind of behavior of typeof has been confirmed as an error. Although it has been corrected, this remains unchanged for post-compatibility purposes. This is why the JavaScript environment has never set a value of null; it must be done programmatically. As mentioned in the MDN document: in api, null is the expected place where objects are frequently searched, but no related objects exist. This applies to DOM, Which is language-independent and does not fall within the scope of ECMAScript specifications. Because it is an external API, an attempt is made to obtain a non-existent element and return a null value instead of undefined. In general, if you need to specify a constant value for a variable or attribute, pass it to a function, or return null from a function, null is almost always the best choice. In short, JavaScript uses undefined and programmers should use null. Another feasible use case of null is also considered to be a good practice. It is explicitly specified that the variable is invalid (object = null) when a reference is no longer necessary. By assigning a null value, the reference is effectively cleared. If the object does not reference other code, specify garbage collection to clear the memory.

In-depth Mining

To make null and undefined look like a black hole is not just their behavior, but their internal processing method in the JavaScript environment. They usually do not have the same associated features as other native or built-in objects. In ES5, Object. PRototype. the toString method has become the actual type check standard, which proves to be consistent in null and undefined: Object. prototype. toString. call (null); // [object Null] Object. prototype. toString. call (undefined); // [object Undefined]

However, the Object. prototype. toString method does not actually retrieve the null internal [[Class] attribute or the undefined public constructor. Follow these steps:

If the value is undefined, "[object Undefined]" is returned.

If the value is null, "[object Null]" is returned.

Let O call ToObject and pass this value as the result value of the parameter.

Make the class the value of the [[Class] internal attribute of O.

The returned results are connected to the string values of the three strings "[object", class, and.

This method executes a simple string return value if it detects that null or undefined is consistent with other objects. This is common in the entire specification, because when null and undefined values are encountered, most methods contain a simple capture and return. In fact, there is no indication that they contain internal properties associated with any native object. It's like they are not objects. I 'd like to know what will happen if an explicit solution exists inside a JavaScript native environment? Some may be more familiar with an implementation that can be involved.

Conclusion

No matter how unusual these native objects are, understanding the differences between null and undefined is a completely different role from their JavaScript language base. It may not make a breakthrough in your application, but in general, it is only proven to be beneficial for the long term in development and debugging.

The above is the content of exploring the abyss of Null and Undefined in JavaScript. For more articles, refer to PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.