During work, we often need to determine whether a variable/attribute is undefined. There are usually two ways to write
Copy codeThe Code is as follows:
// Method 1
Typeof age = 'undefined ';
// Method 2
Age === undefined
Are there any differences between the two statements? Which one should I use? Take a look at the example below
Copy codeThe Code is as follows:
Typeof age = 'undefined'; // true
The identifier age has not been declared and the output is true.
Let's look at another example.
Copy codeThe Code is as follows:
Age === undefined; // Error
Firebug prompt age is not defined,
This is the difference between the two, that is, it is not sure whether the age is declared or defined using method 1, but can be determined using method 2. Method 1: If the variable is not declared, the code will not report an error, but method 2 will report an error. It seems that method 1 has better fault tolerance and is actually a hidden Bug. It is always a good habit to declare and use variables first.
In addition, method 1 is two operations, and method 2 is one operation.