Home  >  Article  >  Web Front-end  >  Analysis of methods to determine null in JS

Analysis of methods to determine null in JS

高洛峰
高洛峰Original
2016-12-06 11:46:091384browse

The example in this article describes the method of judging null in JS. Share it with everyone for your reference, the details are as follows:

The following is the incorrect method:

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

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

Note: This method can be used when you want to judge 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, it will also get the same result as null, although null is different from the two.

Note: This method can be used when you want to judge null, undefined, number 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 it cannot be judged this way.

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

There is the IsNull function in VBScript, but not in JavaScript.

The following 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 numbers zero and false.

The simpler and correct method:

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

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn