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
undefined
As one of the five basic data types of Javascripts, it is also very common in programming. For example, all unassigned variables are setundefined
; Not specifiedreturn
The function of the statement will also returnundefined
; Non-existing object attributes, non-existing array items, and some operators will also returnundefined
Next, 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 specifiedreturn
Return 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
void
The operator evaluates the rear expression, regardless of the result, always returnsundefined
.
var res = void(1+1);res; // undefined
Traps
Althoughundefined
It 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
Forundefined
You 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==
,===
Ortypeof
Operator judgmentundefined
.
var buzz;buzz == undefined; // truebuzz === undefined; // truebuzz == 'undefined'; // falsetypeof buzz == undefined; // falsetypeof buzz == 'undefined'; // true
When using==
Or===
Time andundefined
Comparison of basic type values, usetypeof
Is 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, becauseundefined
It is not a reserved word in Javascript, so we can redefine it in the function.undefined
For 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 thattypeof
To judgeundefined
Value, and the correct result is always returned under any circumstances. To ensure the code is robust, we should always usetypeof
Operator to determineundefined
.
Get undefined using the original literal
var buzz = 'hello';buzz = undefined;buzz; // undefined
Obtained through the void Operator
void
The 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 literalundefined
Simple and Convenient, but in[Determine undefined]In this section, we mentionedundefined
It is not a reserved word in Javascript, and its value can be rewritten in the function scope. However, even ifwindow
,GLOBAL
Object, which can still be overwritten in the function. Thereforewindow
/GLOBAL
Upperundefined
It 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 })();
Thereforevoid
Methodundefined
It becomes a general rule. For example, in underscore. jsisUndefined
It 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
undefined
TransferNumber
Type returnNaN
, ConvertString
Returns the string format.Boolean
Returnfalse
.
// 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 #,null
Indicates 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 andnull
It is defined as "null". When a variable value isnull
The time table does not reference any object entity.
null
Andundefined
There 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
Althoughundefined
Andnull
In JavaScript, it can represent "null, undefined", but there are some minor differences between them:
null
The value must be explicitly specified, and the variable value is
null
The referenced object is null. Set
null
Return 0 when converting to a value,
undefined
Return
NaN
.
var foo = null;typeof foo; // 'object'+ null; // 0+ undefined; // NaN
Summary
typeof
Judgment
undefined
; Use
void 0
Obtain
undefined
;
undefined
And
null
Returns if it is converted to a Boolean value.
false
. Additional reading
Difference between undefined and null
About the void operator in Javascript