How to judge null, undefined, and NaN in JS

Source: Internet
Author: User

In javascript, how does one determine whether a variable is null, undefined, Or NaN? Let's take a look at the specific judgment method.

It is mainly determined through the typeof method. typeof returns a string and has six possible results: "number", "string", "boolean", "object", "function", and "undefined ".

1. Determine undefined:

var tmp=undefined;if(typeof(tmp)=="undefined"){    alert("undefined");}

2. null judgment:

var tmp=null;if(!tmp&&typeof(tmp)!="undefined"&&tmp!=0){    alert("null");}

3. Judge NaN:

var tmp=0/0;//www.phpernote.comif(isNaN(tmp)){    alert("NaN");}

Note: If the result of comparing NaN with any value (including its own) is false, you cannot use the = OR = Operator to determine whether a value is NaN.

Tip: The isNaN () function is usually used to check the results of parseFloat () and parseInt () to determine whether they represent valid numbers. Of course, you can also use the isNaN () function to detect arithmetic errors, such as using 0 as the divisor.

4. Determine undefined and null:

var tmp=undefined;if(tmp==undefined){    alert("null or undefined");}

Or:

var tmp=undefined;if(tmp==null){    alert("null or undefined");}

Description: null = undefined

5. Determine undefined, null, and NaN:

var tmp=null;if(!tmp){    alert("null or undefined or NaN");}

Tip: Generally, this is enough to differentiate data.

Articles you may be interested in
  • How does js determine the undefined type?
  • Summary of JS methods for determining browser types (IE firefox chrome opera safari)
  • How to solve the Call to undefined function curl_init error in php running?
  • Fatal error Call to undefined function date_default_timezone_set ()
  • Php prompts Call to undefined function curl_init () Error Solution
  • The last record of the volist loop in the thinkphp Template
  • Javascript checks whether the object is empty.
  • Solution to the DedeTag Engine Create File False error in dedeCMS

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.