Two differences between JavaScript statements for determining whether a variable is undefined _ javascript skills

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.