At work, we often need to determine whether a variable/property is undefined. There are usually two ways of writing
Copy the code code as follows:
// Method 1
typeof age === 'undefined';
// Method 2
age === undefined
Is there any difference between these two ways of writing? Which one should be used? Take a look at the following example
Copy the code code as follows:
typeof age === 'undefined'; // true
The identifier age has not been declared, and true is output.
Let’s look at another example
Copy the code code as follows:
age === undefined; // Error report
Firebug prompts age is not defined,
This is the difference between the two, that is, if you are not sure whether age is declared or defined, use method 1, and if you are sure, you can use method 2. If the variable is not declared using method 1, the code will not report an error, but method 2 will report an error. It seems that method 1 is more fault-tolerant, but in fact it is a hidden bug. It is always a good practice to declare variables before using them.
In addition, method 1 is two operations and method 2 is one operation.