Learn the undefined and null_javascript skills of JavaScript with me

Source: Internet
Author: User
Tags garbage collection reserved

When discussing the raw data types in JavaScript, most people know the basics from string, number to Boolean. These primitive types are fairly simple and behave in a common sense. However, this article will focus more on the unique raw data types null and undefined, what makes them so similar, but specious.

I. Understanding null and undefined

In JavaScript, NULL is a literal and is also a keyword in the language, used to represent unrecognized object values. In other words, this is meant to mean "no value", but you can decide when to expect it.

Although similar, undefined actually represents a nonexistent value (Non-existence of a), which means you have something missing. Both are completely immutable, with no properties and methods, and cannot be assigned a value to its properties. In fact, when you attempt to access or define a property of null and undefined, a type error (TypeError) is raised.

A Boolean value that is not represented by a value is false, which means that they are evaluated as false in the context of the condition, such as an if statement. Using the equality operator (= =) to compare these two values and other false values, they are not equal to except themselves:

NULL = = 0; False 
undefined = = ""; False 
NULL = = FALSE;//false 
undefined = = false;//false 
null = undefined;//True 

However, as with other similarities, null and undefined are not equivalent. Each unique member of its distinct type, undefined is the undefined type and null is the object type. Use the strict equality operator (= = =) To compare these two values, which require both types and values to be equal, as evidenced by the following:

Null = = = undefined; False
typeof null;//"Object"
typeof undefined;//"Undefined"

It says: null This is an object, but is empty. And null is the JAVASCRIPT reserved keyword.
When NULL participates in numeric operations, its value is automatically converted to 0, so the following expression evaluates to the correct number:

123 + null;   123 
123 * NULL; 0 

Undefined is a special property of the Global Object (window) whose value is undefined. But typeof undefined returned to ' undefined '.
Although undefined has a special meaning, it is indeed a property and is a property of the Global Object (window). Take a look at the following code:

Alert (' Undefined ' in window);//output: True 
var anobj = {}; 
Alert (' undefined ' in anobj); Output: false 

As you can see, undefined is a property of the Window object, but it is not a property of the Anobj object.
Note:

    • Although undefined is a property of special meaning, it is not a reserved keyword for JavaScript. Undefined participates in any numerical calculation, the result must be Nan. By the way, Nan is another special property of the Global Object (window), infinity. These special properties are not javascript reserved keywords!
    • To verify that a value or an object is null, you need to use "= = =" To determine, if only "= =", you can not determine whether null or undefined.

Second, the emergence of undefined situation
There are many ways to generate a undefined value code. It is commonly encountered when attempting to access a value that does not exist. In this case, in the dynamic, weakly typed language of JavaScript, only a undefined value is returned by default instead of rising to an error.

1, any declaration of a variable does not provide an initial value, there will be a default value of undefined:

 
 

2. Returns a undefined value when attempting to access an object property or array item that does not exist:

var array = [1, 2, 3]; 
var foo = Array.foo; The Foo property does not exist, returns undefined 
var item = array[5];//an item with no index 5 in the array, returns the undefined 

3, if the return statement of the function is omitted, or the return statement takes no arguments back to undefined:

var value = (function () {

}) ();//returns undefined 
var value1 = (function () {return
  ;
}) (); Back to undefined 

4. When calling a function, the supplied parameter is not supplied, which equals undefined

function f (x) {
  console.log (x)
}
f ();//undefined

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

' undefined ' in window; True 

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

Three, null use cases

The null use case is the main aspect that makes him different, because unlike Undefined,null is considered to be more useful. This is why the TypeOf operator returns "Object" when acting on a null value. The original reason is that it is still, and is often used as an expectation of a null reference to an empty object, like a placeholder. This behavior of TypeOf has been identified as a mistake, although the amendment has been made, and this has remained unchanged for later compatibility purposes.

In general, if you need to assign an invariant value to a variable or attribute, pass it to a function, or return null,null from a function is almost always the best choice. In short, JavaScript uses undefined and programmers should use NULL.

Another viable use case for Null is also considered a good practice to be an explicitly specified variable to be invalid (object= null) when a reference is no longer required. Effectively clears the reference by assigning null values, and assumes that the object does not reference other code, specifies garbage collection, and ensures that the memory is reclaimed.

Iv. improve the performance of undefined

When we use the undefined value in a program, we actually use the undefined property of the Window object. Similarly, when we define a variable but do not give its initial value, for example:

 
 

At this point, JavaScript sets its initial value to a reference to the Window.undefined property when it is called precompilation, so when we compare a variable or value to a undefined, it is actually compared to the undefined property of the Window object. During this comparison, JavaScript searches for the properties of the window object called ' undefined ', and then compares the reference pointers of the two operands to the same.

Because the property values of the Window object are very numerous, it takes time to search for the undefined property of the Window object in each comparison with the undefined. This can be a performance problem in a function that requires frequent comparisons with undefined. Therefore, in this case, we can define a local undefined variable to speed up the comparison of undefined. For example:

function Anyfunc () { 
  var undefined; 
  Custom local undefined variable 
  if (x = = undefined) 
  //scope references compare while 
  (y!= undefined) 
  //Scope reference comparison 
}; 

Where the undefined local variable is defined, its initial value is a reference to the Window.undefined property value. The newly defined local undefined variable exists on the scope of the function. In subsequent comparisons, the JavaScript code was written in a way that was not changed, but was relatively fast. Because the number of variables on the scope is much less than the properties of the Window object, the speed of the search variable can be greatly improved.

This is why many front-end JS frameworks often have to define a local undefined variable for themselves!

The above is the entire content of this article, I hope to help you learn.

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.