How do I check for null values in JavaScript?

Go To StackoverFlow.com

452

How can I check for null values in JavaScript? I wrote the code below but it didn't work.

if (pass == null || cpass == null || email == null || cemail == null || user == null) {      

    alert("fill all columns");
    return false;  

}   

And how can I find errors in my JavaScript programs?

2011-05-14 18:15
by Mahdi_Nine
Are you sure the values you are testing are actually null and not just empty string - Jan-Peter Vos 2011-05-14 18:18
testing null in js should be done with the strict operator ===davin 2011-05-14 18:19
@Hogan, I meant strict, and I assume by the upvotes that the readers interpreted it that way.. - davin 2011-05-14 18:22
@davin - true, but not the problem here since if it were the statement would still work - Mark Kahn 2011-05-14 18:22
@cwolves, if I thought it were the problem I would have made that comment an answer. Check out my wording, I'm clearly making a general statement about the language in reference to the OP's practise, and not proposing that this solves his problem - davin 2011-05-14 18:24
@ic3b3rg I think I agree with your rollbacks, but I'd be happier if you explained them - TRiG 2014-07-18 10:55
@TRiG the proposed changes fundamentally alter the nature of the question to the point where the answers (not just mine) lose context and don't make sense. The edit should just be a comment - ic3b3rg 2014-07-22 04:50


615

Javascript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:

if(!pass || !cpass || !email || !cemail || !user){

Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN

Please note that if you are specifically checking for numbers it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf)

2011-05-14 18:20
by Mark Kahn
It would be very useful to know which parts of this test for which values. Sometimes you're looking for one in particular - inorganik 2013-04-19 19:28
Somewhat of a late statement, but yes, you can perform test against each one @inorganik , see my answer belo - WebWanderer 2014-12-18 16:02
Readers, please be careful when using this type of test on numeric data. Do not use ! or !! to test for null or undefined on typically-numeric data unless you also want to throw away values of 0 - NickS 2016-02-24 21:06
Have to agree with NickS. If you're specifically testing for null, it's possible to get false positives with this type of boolean NOT test. This is an overbroad solution to a specific question - YiddishNinja 2016-06-24 19:35
The answer itself states this: "...and the numbers 0...". I believe this answer is perfectly appropriate for the question as given the context (which I'm inferring is "username, password, email"), they're not checking for 0 values. Given the popularity of this question and answer, however, I agree that it's worth mentioning in the answer itself - Mark Kahn 2016-06-24 20:13
This is not actually answering the question. It's based on a guess: "I'm guessing you're actually looking for empty strings." The question concerns checking for null values. @WebWanderer has the correct solution - Hendeca 2016-07-02 00:31
@Hendeca - rolls eyes Go read the code in the actual question. It's clearly asking about usernames and passwords. I'm not guessing at anything, I was just being polite. You're bothered by the fact that I answered what they needed and not what they asked, which is absurd. This is SO, most of the time people don't know what they should be asking for. In the context of the original question this answer is correct. Now stop adding noise - Mark Kahn 2016-07-04 01:34
@zyklus Even if he is asking about usernames and passwords, it's possible that functions could be gathering the data from the forms and returning null if an empty string is found. But much more importantly, Stack Overflow questions come up as google results all the time, so many people who are curious how to check for a null value will be directed here and will see your answer first. It probably would have been best to answer the question that was asked and then address the specifics of this code. Sorry if that upsets you, SO asks me to comment when I downvote an answer so I am doing that - Hendeca 2016-07-04 01:44
@Hendeca - The context of answering a question for the 420,000 people that have seen this question is very different than the context of answering it for the OP. I'll consider re-wording the answer - Mark Kahn 2016-07-04 02:08


294

To check for null SPECIFICALLY you would use this:

if(variable === null && typeof variable === "object")

...or more simply:

if(variable === null)

This test will ONLY pass for null and will not pass for "", undefined, false, 0, or NaN.

The rest of this is in response to inorganik's comment, Yes, you can check each one individually.

You need to implement use of the absolutely equals: === and typeof to be absolutely sure with your checks.

I've created a JSFiddle here to show all of the individual tests working

Here is all of the output of the tests:

Null Test:

if(variable === null && typeof variable === "object")

- variable = ""; (false) typeof variable = string

- variable = null; (true) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Empty String Test:

if(variable === "" && typeof variable === "string")

- variable = ""; (true) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number




Undefined Test:

if(variable === undefined && typeof variable === "undefined")

- variable = ""; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (true) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



False Test:

if(variable === false && typeof variable === "boolean")

- variable = ""; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (true) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Zero Test:

if(variable === 0 && typeof variable === "number")

- variable = ""; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (true) typeof variable = number

- variable = NaN; (false) typeof variable = number



NaN Test:

if(!parseFloat(variable) && variable != 0 && typeof variable === "number")

- variable = ""; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (true) typeof variable = number

As you can see, it's a little more difficult to test against NaN;

2014-12-18 16:01
by WebWanderer
What is the purpose of type checking if you use === strict equality? Thanks.

Also for NaN test you can use isNaN(value) that will return true only if variable equals NaN - Michael Malinovskij 2015-02-11 13:20

Sanity check, plus, you'd be surprised how many times I've used an absolutely equals and not received a proper value in return with checking typeof. lol. Also, I've had some issues with isNaN in the past, so I decided to provide what is an absolutely sure-fire way to check each one. There should be no case failure on any of these checks. You're welcome - WebWanderer 2015-02-11 18:10
Is there a case where variable === null but is not of type "object"? If there is not, why not simplify the check to variable === null, throwing out the second conjunct? Thanks - Hunan Rostomyan 2015-04-04 22:19
@HunanRostomyan Good question, and honestly, no, I do not think that there is. You are most likely safe enough using variable === null which I just tested here in this JSFiddle. The reason I also used && typeof variable === 'object' was not only to illustrate the interesting fact that a null value is a typeof object, but also to keep with the flow of the other checks. But yes, in conclusion, you are safe to use simply variable === null - WebWanderer 2015-04-06 14:59
https://jsfiddle.net/neoaptt/avt1cgem/1/ Here is this answer broken out into functions. Not very usefull, but I did it anyways - Neoaptt 2016-04-18 18:22


56

just replace the == with === in all places.

== is a loose or abstract equality comparison

=== is a strict equality comparison

See the MDN article on Equality comparisons and sameness for more detail.

2011-05-14 18:27
by ic3b3rg
I can't stand "Just do this..." answers without explanation to why someone should do something - John 2016-01-05 17:40
This only works if you consider undefined to be not null. Otherwise it will lead to a lot of unexpected behavior. Generally if you're interested in both null/undefined but not falsy values, then use == (one of the few cases when you should do so) - Andrew Mao 2016-05-11 22:40
@AndrewMao undefined is not null: http://stackoverflow.com/a/5076962/75323 - ic3b3rg 2016-06-27 02:18
I believe that's what @AndrewMao was saying, really. His first sentence might be rewritten "This only works in situations where undefined and null are not practical equivalents. - BobRodes 2016-06-30 02:22
@BobRodes Thanks for clarifying my poor writing, I appreciate it : - Andrew Mao 2016-06-30 15:16
@AndrewMao You are very welcome. And I wouldn't call your writing poor, personally; I'd say it's a good deal better than average. : - BobRodes 2016-06-30 18:23


24

Strict equality operator:-

We can check null by ===

if ( value === null ){

}

Just by using if

if( value ) {

}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • false
  • 0
2016-07-05 11:58
by Arshid KV


6

Firstly, you have a return statement without a function body. Chances are that that will throw an error.

A cleaner way to do your check would be to simply use the ! operator:

if (!pass || !cpass || !email || !cemail || !user) {

    alert("fill all columns");

}
2011-05-14 18:20
by Joey C.
That code is probably in a function, he just didn't show it ; - Mark Kahn 2011-05-14 18:22


5

Improvement over the accepted answer by explicitly checking for null but with a simplified syntax:

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
}

// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
    console.log ("Yayy! None of them are null");
} else {
    console.log ("Oops! At-lease one of them is null");
}

2018-03-14 03:45
by deekshith


4

you can use try catch finally

 try {
     document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
 } catch (e) {

     if (e.name.toString() == "TypeError") //evals to true in this case
     //do something

 } finally {}   

you can also throw your own errors. See this.

2011-05-14 18:25
by DrStrangeLove
i think this qualifies as 'paranoid' code. if you really wrote something like this, it would be with an understanding that "mydiv" couldn't possibly not exist. we shouldn't reach this code unless we're confident that's the case, and we'd have plenty of avenues such as response codes to make sure we're confident before attempting such a line - calql8edkos 2015-05-05 16:09


4

to check for undefined and null in javascript you need just to write the following :

if (!var) {
        console.log("var IS null or undefined");
} else {
        console.log("var is NOT null or undefined");
}
2015-02-25 10:48
by Nejmeddine Jammeli
!var is true with 0, "", NaN, and false, too - Matt 2015-08-13 16:10


3

This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as

if(!parseInt(variable) && variable != 0 && typeof variable === "number")

but this will fail for rational numbers which would round to 0, such as variable = 0.1. A better test would be:

if(isNaN(variable) && typeof variable === "number")
2015-02-18 19:10
by Gabriel
Thanks for pointing out the bug Gabriel, I've put the fix into my answer. Aside from that, I was able to fix the test by changing parseInt to parseFloat (which should have been obvious to me in the first place). I avoided using the isNan function because I feel as if many developers view functions such as isNaN as some sort of "magic box" that values go into and booleans come out of, and I wanted to should the test a little more in depth. But yes, your suggested test will work and is perfectly fine to use. Sorry I didn't notice your post until now - WebWanderer 2015-04-16 15:06
Great, that seems to work. Thanks for the comment on why you avoided isNaN as well, I can get behind that logic. There's also the Underscore.js method, which seems even more confusing/blackbox, but worth noting anyway because it takes advantage of NaN !== NaN. Object.prototype.toString.call(variable) === '[object Number]' && variable !== +variableGabriel 2015-04-18 00:23
Ooh! That's actually pretty cool! Thanks for the info Gabe - WebWanderer 2015-04-20 14:33


3

In JavaScript, no string is equal to null.

Maybe you expected pass == null to be true when pass is an empty string because you're aware that the loose equality operator == performs certain kinds of type coercion.

For example, this expression is true:

'' == 0

In contrast, the strict equality operator === says that this is false:

'' === 0

Given that '' and 0 are loosely equal, you might reasonably conjecture that '' and null are loosely equal. However, they are not.

This expression is false:

'' == null

The result of comparing any string to null is false. Therefore, pass == null and all your other tests are always false, and the user never gets the alert.

To fix your code, compare each value to the empty string:

pass === ''

If you're certain that pass is a string, pass == '' will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.

If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.

2015-08-27 23:28
by Michael Laszlo


1

Actually I think you may need to use if (value !== null || value !== undefined) because if you use if (value) you may also filter 0 or false values.

Consider these two functions:

const firstTest = value => {
    if (value) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}
const secondTest = value => {
    if (value !== null && value !== undefined) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}

firstTest(0);            // result: failed
secondTest(0);           // result: passed

firstTest(false);        // result: failed
secondTest(false);       // result: passed

firstTest('');           // result: failed
secondTest('');          // result: passed

firstTest(null);         // result: failed
secondTest(null);        // result: failed

firstTest(undefined);    // result: failed
secondTest(undefined);   // result: failed

In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.

2018-11-04 14:52
by Naeem Baghi


0

Please view carefully before downvote.

AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined. so we can check variable even if it would be an object holding some instance in place of value.

create a helper method for checking nullity that returns true and use it in your API.

helper function to check if variable is empty:

function isEmpty(item){
    if(item){
        return false;
    }else{
        return true;
    }
}

try-catch exceptional API call:

try {

    var pass, cpass, email, cemail, user; // only declared but contains nothing.

    // parametrs checking
    if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
        console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
    }else{
        // do stuff
    }

} catch (e) {
    if (e instanceof ReferenceError) {
        console.log(e.message); // debugging purpose
        return true;
    } else {
        console.log(e.message); // debugging purpose
        return true;
    }
}

some test cases:

var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true

console.log("isEmpty? "+isEmpty(item));
2015-10-05 14:46
by Kaleem Ullah
What? This answer has nothing to do with this post. Did you post this answer on this thread by accident - WebWanderer 2015-11-02 20:32


0

This will not work in case of Boolean values coming from DB for ex:

 value = false

 if(!value) {
   // it will change all false values to not available
   return "not available"
 }
2016-05-23 06:48
by Codiee


-1

Try this:

if (!variable && typeof variable === "object") {
    // variable is null
}
2015-11-03 14:23
by user5520516
null is only thing that is "falsy" and typeof returns "object" - user5520516 2015-11-03 14:25
How is that better than if (variable === null)? Also someone already provided that answer last year: http://stackoverflow.com/a/27550756/218196 - Felix Kling 2015-11-03 14:44
Ads