SoFunction
Updated on 2025-02-28

Analysis of the method of judging null in JS

This article describes the method of judging null in JS. Share it for your reference, as follows:

Here are the incorrect methods:

var exp = null;
if (exp == null)
{
  alert("is null");
}

When exp is undefined, the same result as null is also obtained, although null and undefined are different.

Note: This method can be used when judging null and undefined at the same time.

var exp = null;
if (!exp)
{
  alert("is null");
}

If exp is undefined, or the number zero, or false, you will also get the same result as null, although null is different from the two.

Note: This method can be used when judging null, undefined, zero, and false at the same time.

var exp = null;
if (typeof exp == "null")
{
  alert("is null");
}

For backward compatibility, when exp is null, typeof null always returns object, so this cannot be judged.

var exp = null;
if (isNull(exp))
{
  alert("is null");
}

The IsNull function is available in VBScript, but not in JavaScript.

Here is the correct way:

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

typeof exp != "undefined" excludes undefined;

exp != 0 Excludes the number zero and false.

The simpler correct way to do it:

var exp = null;
if (exp === null)
{
  alert("is null");
}

Despite this, in DOM applications, we generally only need to use (!exp) to judge, because in DOM applications, null may be returned or undefined may be returned. If we specifically judge whether null or undefined, the program will be too complicated.

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of json operation skills in JavaScript》、《Summary of JavaScript switching effects and techniques》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript animation special effects and techniques》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.