JavaScript distinguishes between the two ways of writing a variable to determine whether it is undefined

  • 2020-03-30 00:40:54
  • OfStack

At work we often need to determine whether a variable/property is undefined. There are usually two ways to write it


//Method 1
typeof age === 'undefined'; 

//Way 2
age === undefined 

What's the difference? Which one should I use? Take a look at the following example

typeof age === 'undefined'; // true 

The identifier age is not declared, and the output is true.

Let's do another example


age === undefined; //  An error  

Firebug says age is not defined,

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201312/2011061713505317.png ">

This is the difference between the two, that is, if you are not sure whether age is declared or defined, you can use mode 1; if you are sure, you can use mode 2. Use mode 1: if the variable is not declared, the code will not report an error, but mode 2 will report an error. It seems that way 1 is more fault-tolerant, but actually it will be a latent Bug. It is always a good habit to declare variables before using them.

In addition, mode 1 is two operations and mode 2 is one.


Related articles: