This article mainly introduces in detail the differences between the two writing methods for JavaScript to determine whether the variable is undefined. If you need a friend, refer to it, I hope it will be helpful to you. In our work, we often need to determine whether a variable/attribute is undefined. There are usually two ways to write
The 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
The 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.
The 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.