Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 17:10:51
Original
1227 people have browsed it

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template