Home  >  Article  >  Web Front-end  >  The difference between two ways of writing JavaScript to determine whether a variable is undefined_javascript skills

The difference between two ways of writing JavaScript to determine whether a variable is undefined_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:511223browse

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

Copy code The code is 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? Woolen cloth? Look at the example below
Copy the code The code is as follows:

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

The identifier age has not been declared, output true.

Look at another example

Copy the code The code is as follows:

age === undefined; // Error report

Firebug prompts that 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn