Home >Web Front-end >JS Tutorial >How to determine null value using js

How to determine null value using js

小云云
小云云Original
2017-11-18 16:00:043468browse

We often judge a null value when developing, so how should we judge it? This article will teach you how to use js to determine the null value. Two methods are used to compare how to correctly use js to determine the null value.

The following is an incorrect approach:

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

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

Note: When you want to judge null and undefined at the same time, you can use the above method.

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

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

Note: If you want to judge null, undefined, number zero, and false at the same time, you can use the above method.

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 method:

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

typeof exp!="undefined" excludes undefined

exp!=0 excludes Number zero and false.

Simpler and correct method:

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

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

The above is how to use js to determine null. I hope it will be helpful to everyone.

Related recommendations:

Why does JavaScript have null? (Translation) - Tianbeiya

What is the original design intention of null and undefined in js

How to use MySQL database to determine NULL The result is 1?

The above is the detailed content of How to determine null value using js. For more information, please follow other related articles on the PHP Chinese website!

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