Exploring undefined in js

Source: Internet
Author: User

Exploring undefined in js
Background

If you know Java, you will know that the attributes not assigned in the class will be assigned the initial value by the compiler during compilation. Unlike some static languages such as Java and C #, Javascript is an interpreted Dynamic Language. Because there is no compilation link, its variable type can be changed dynamically when the program is running. This weak type determines that an open and meaningless value should be used as the initial value of the variable in Javascript design.undefined.

Exploration

undefinedAs one of the five basic data types of Javascripts, it is also very common in programming. For example, all unassigned variables are setundefined; Not specifiedreturnThe function of the statement will also returnundefined; Non-existing object attributes, non-existing array items, and some operators will also returnundefinedNext, let's explore togetherundefined.

Variable

Most commonly, unassigned global or local variables will returnundefined.

Var buzz; // undefined, global variable (fucntion (arg) {var fizz; console. log (arg); // undefined, parameter variable console. log (fizz); // undefined, local variable })();
Function

Each function has a return value. If this parameter is not specifiedreturnReturn Value. By defaultundefined.

Var fn1 = function () {}; fn2 = function () {return;} var res1 = fn1 (); res2 = fn2 (); console. log (res1); // undefined, omitting returnconsole. log (res2); // undefined, return value not specified
Array

Returns an undefined data entry in the access array.undefined.

var arr = [1,2];arr.length = 5;console.log(arr[3]);      // undefinedconsole.log(arr[10]);     // undefined
Object

Returned value of the undefined attribute on the Access Objectundefined.

var person = {     name:Lee,};person.age;     // undefined     
Operator

voidThe operator evaluates the rear expression, regardless of the result, always returnsundefined.

var res = void(1+1);res;     // undefined
Traps

AlthoughundefinedIt indicates "Missing Value", which should have a value, but is not defined yet. At the same time, one of the other basic type variables in JavaScriptnull, There is also the meaning of "null reference, undefined" object, beginners often confuse the two, sometimes a little less attention will fall into the trap.

Undefined usage

ForundefinedYou must keep in mind the usage of judgment, acquisition, and transformation. Unexpected results may occur if you rely on experience in other languages.

Determine undefined

Available==,===OrtypeofOperator judgmentundefined.

var buzz;buzz == undefined;             // truebuzz === undefined;            // truebuzz == 'undefined';           // falsetypeof buzz == undefined;      // falsetypeof buzz == 'undefined';    // true

When using==Or===Time andundefinedComparison of basic type values, usetypeofIs compared with the string. Are these methods safe and reliable? Let's continue to look at the following example:

(function() {    var undefined = 'hello';    var buzz;    console.log(buzz == undefined);             // false    console.log(buzz === undefined);            // false    console.log(typeof buzz == 'undefined');    // true})();

This is a self-called function, becauseundefinedIt is not a reserved word in Javascript, so we can redefine it in the function.undefinedFor the original value, only the external global scope can be obtained:

Window. undefined; // the browser environment is GLOBAL. undefined; // Node environment (function () {var undefined = 'hello'; var buzz; console. log (undefined); // 'hello' console. log (buzz = window. undefined); // true console. log (buzz = window. undefined); // true console. log (typeof buzz = 'undefined'); // true })();

To sum up the above results, we can see thattypeofTo judgeundefinedValue, and the correct result is always returned under any circumstances. To ensure the code is robust, we should always usetypeofOperator to determineundefined.

Get undefined using the original literal
var buzz = 'hello';buzz = undefined;buzz;     // undefined
Obtained through the void Operator

voidThe operator evaluates the rear expression, regardless of the result, always returnsundefined.

var buzz = 'hello';buzz = void 0;typeof buzz === 'undefined';    // true
Best practices

Although it is obtained through the original literalundefinedSimple and Convenient, but in[Determine undefined]In this section, we mentionedundefinedIt is not a reserved word in Javascript, and its value can be rewritten in the function scope. However, even ifwindow,GLOBALObject, which can still be overwritten in the function. Thereforewindow/GLOBALUpperundefinedIt is not 100% reliable. For example:

(function() {     var undefined = 'hello',         foo = {},        window = {             'undefined': 'world'        };     console.log(undefined);              // 'hello'    console.log(window.undefined);       // 'world'    console.log(foo.a === undefined);    // false     console.log(foo.a === void 0);       // true })();

ThereforevoidMethodundefinedIt becomes a general rule. For example, in underscore. jsisUndefinedIt is written in this way:

_.isUndefined = function(obj) {    return obj === void 0;}

Another way is to use the default value of function parameters. For example, AngularJS uses the following method in the source code:

(function(window, document, undefined) {    //.....})(window, document);

"undefined"The parameter is omitted to ensure that its value is a default value.undefined.

Undefined Transformation

undefinedTransferNumberType returnNaN, ConvertStringReturns the string format.BooleanReturnfalse.

// Display and convert Number (undefined); // NaNString (undefined); // 'undefined' Boolean (undefined); // false // implicitly convert 1 + undefined; // NaN, implicitly converted to 'str' + undefined; // 'strundefined', implicitly converted to stringif (undefined) {console. log (true); // will not be output} else {console. log (false); // false, implicitly converted to boolean}
Null

In some object-oriented languages such as Java and C #,nullIndicates a null reference. When an initial value is declared for a referenced variable in the class, the compiler automatically initializes the reference valuenull. JavaScript draws on this design andnullIt is defined as "null". When a variable value isnullThe time table does not reference any object entity.
nullAndundefinedThere is a certain degree of similarity in performance.if()The statement will be automatically convertedfalse, Use"=="The operators are equal to each other.

var buzz = undefined;    fizz = null;if (buzz) {    console.log(buzz + ' is true');} else {    console.log(buzz + ' is false');}// undefined is falseif (fizz) {    console.log(fizz + ' is true');} else {    console.log(fizz + ' is false');}// null is falseundefined == null;      // true

AlthoughundefinedAndnullIn JavaScript, it can represent "null, undefined", but there are some minor differences between them:

nullThe value must be explicitly specified, and the variable value is nullThe referenced object is null. Set nullReturn 0 when converting to a value, undefinedReturn NaN.
var foo = null;typeof foo;     // 'object'+ null;         // 0+ undefined;    // NaN
Summary typeofJudgment undefined; Use void 0Obtain undefined; undefinedAnd nullReturns if it is converted to a Boolean value. false. Additional reading

Difference between undefined and null
About the void operator in Javascript

 

Related Article

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.