Javascript determines whether the variable is undefined.

Source: Internet
Author: User

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

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

Are there any differences between the two statements? Which one should I use? Take a look at the example below

 
Typeof age = 'undefined'; // true

The identifier age has not been declared and the output is true.

Let's look at another example.

 
Age === undefined; // Error

Firebug promptAge 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,CodeNo error is reported, but method 2 reports 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.