A method to obtain pure undefined in JavaScript

  • 2021-01-25 06:55:55
  • OfStack

1. Why do you want to get undefined??

Because undefined is not reserved in javascript, it can be assigned as a variable by the user, so if we need to use undefined to detect a variable later, then the value detected is not accurate;

For example:


var undefined=10;
function sum(a,b){
 if(a===undefined||b===undefined){
  console.log(" Incorrect parameter ");
 }18101130357
 return a+b;
}

sum(10,10)- > Originally correct parameters, the console output is true "parameter error";

At this point, in order to be compatible with all browsers, we need to get a pure undefinde

2. How to get pure undefined?

1) void (0):

In the ECMAScript 262 specification, it is described as follows:


The void Operator
The production UnaryExpression : void UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Call GetValue(expr).
Return undefined.

Anyway, remember that no matter what the expression after void is, the void operator will always return undefined

2) Pass in a parameter that is assigned

[case]


function(_undefined){
// The body of the function is not given _undefined Assignment, parameter _undefined The value is undefined , can be used in this function _undefined the 
}

3) Unassigned variables

For example, var num // is the same as 2)

Don't get bored with the familiar. Make 1 point a day. Don't be afraid of new things. Learn something every day.

PS: js determines the type of undefined


 if (reValue== undefined){
 alert("undefined");
 }
  Found to judge not to come out, finally checked the next information to use typeof
 Methods: 
if (typeof(reValue) == "undefined") { 
 alert("undefined"); 
}

typeof returns a string with 6 possibilities: "number", "string", "boolean", "object", "function", "undefined"


Related articles: