Learn javascript undefined and null_javascript skills

Source: Internet
Author: User
Learn about undefined and null in javascript, understand null and undefined in definition, and tell you how to improve the performance of undefined, if you are interested, you can refer to the discussion on 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. What makes them so similar, but it is similar.

1. Understand 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", but you can decide when to get the expected value.

Although similar, undefined actually represents non-existence of a value, that is, something is lost. Both are completely immutable. No attribute or method can be used to assign a value to its attribute. In fact, when you try to access or define a property of null and undefined, a type error is thrown ).

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; // false undefined == ""; // false null == false; // false undefined == false; // false null == 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 Object type. Compare the two values by using the equal-Sum Operator (=), which requires that the types and values are equal. The following demonstrates this:

null === undefined; //falsetypeof null; //"object"typeof undefined; //"undefined"

The above description: null is an object, but it is null. And null is the reserved keyword in JavaScript.
In addition, the value of null is automatically converted to 0 when involved in the numeric operation. Therefore, the following expressions obtain the correct value after calculation:

123 + null;   //123 123 * null;   //0 

Undefined is a special attribute of a Global Object (window). Its value is undefined. However, typeof undefined returns 'undefined '.
Although undefined has a special meaning, it is indeed an attribute and a Global Object (window) attribute. See the following code:

Alert ('undefined' in window); // output: true var anObj ={}; alert ('undefined' in anObj); // output: false

It can be seen that undefined is an attribute of the window object, but it is not an attribute of the anObj object.
Note:

  • Although undefined is an attribute with special meanings, it is not a reserved keyword of JavaScript. When undefined participates in any numerical calculation, the result must be NaN. Just put, NaN is another special attribute of the Global Object (window), and Infinity is also. These special attributes are not reserved keywords of JavaScript!
  • When verifying a value or an object is null, you must use "=" to determine whether it is null or undefined.

Ii. Undefined generation
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.

1. If no initial value is provided when a variable is declared, a default value of undefined will exist:

Var foo; // The default value is undefined.

2. 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 returned value is undefined var item = array [5]; // if no index is 5 in the array, the returned value is undefined.

3. If the return Statement of the function is omitted, or the return statement does not include any parameters, undefined is returned:

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

4. When calling a function, the required parameter is not provided. This parameter is equal to undefined.

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

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.

Iii. null 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 a correction is proposed, this remains unchanged for the purpose of post compatibility.

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.

4. Improve undefined Performance

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

var aValue; 

In this case, JavaScript sets its initial value to window during the so-called pre-compilation. the reference of the undefined attribute. Therefore, when we compare a variable or value with undefined, it is actually compared with the undefined attribute of the window object. During this comparison, JavaScript searches for the properties of the window object named 'undefined', and then compares whether the reference pointers of the two operands are the same.

Because the window object has many attribute values, it takes time to search for the undefined attribute of the window object during each comparison with undefined. This may be a performance issue in functions that need to be frequently compared 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) // compare references in the scope of while (y! = Undefined) // reference comparison in the scope };

When undefined local variables are defined, the initial value is a reference to the window. undefined attribute value. The newly defined partial undefined variation exists in the scope of the function. In subsequent comparison operations, the writing method of JavaScript code has not changed, but the comparison speed is fast. Because the number of variables in the scope will be much less than the properties of the window object, the speed of searching for variables will be greatly improved.

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

The above is all the content of this article, hoping 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.