JS determines whether the variable is undefined

Source: Internet
Author: User

There are two special data types in JavaScript: undefined and null, and let's talk about undefined's judgment.

JS Judge undefined type

The code is as follows Copy Code
if (revalue== undefined) {
Alert ("undefined");
}

Found that the judge does not come out, finally checked the data to use typeof

Method:

The code is as follows Copy Code


if (typeof (revalue) = = "undefined") {
Alert ("undefined");
}

typeof returns a string of six possible: "Number", "string", "Boolean", "Object", "function", "undefined"


The following is an incorrect usage:

The code is as follows Copy Code

var exp = undefined;
if (exp = = undefined)
{
Alert ("undefined");
}

When exp is null, it also gets the same result as undefined, although null and undefined are different. Note: This method can be used to determine both undefined and null.


The following are the correct uses:

The code is as follows Copy Code

var exp = undefined;
if (typeof (exp) = = "undefined")
{
Alert ("undefined");
}

Pay attention to whether it is undefined to be sure to add quotation marks on both sides, otherwise it will not succeed (personal test results!)


instance

A variable var bank_value, when alert him, some of his values are undefined, so I use the following to determine whether he equals undefined.

The code is as follows Copy Code

var Yinvalue;

if (yinvalue== ' undefined ')
{
Break
}

It turned out to be wrong, without entry conditions. Later on the Internet check, very simple as follows:

The code is as follows Copy Code

if (typeof (yinvalue) = = ' undefined ')
{
Break
}

typeof returns a string of six possible: "Number", "string", "Boolean", "Object", "function", "undefined"

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.