How do I check for null values in JavaScript?


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?

7/23/2020 1:15:09 PM

Accepted Answer

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)

6/24/2016 8:17:01 PM

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.


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

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");


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");


you can use try catch finally

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

     if ( == "TypeError") //evals to true in this case
     //do something

 } finally {}   

you can also throw your own errors. See this.