Note: Most people confuse null variables with undefined and empty variables for being the same.
Example 1: Checking for Null variable with if – else statement
Simply start by creating a variable and setting its value equal to the keyword null with the following line:
Create another variable with some value in it with the help of the following line:
After that, we are going to create a function that will check variables for a null variable:
if (ourVar !== null) {
console.log("Not a Null variable");
} else {
console.log("Null variables Detected");
}
}
This function simply uses an if-else statement. After that, we are going to pass both our variables one by one to the function checkNull():
checkNull(y);
Executing this program will provide us with the following result:
The first line in the output is for the variable “x” and from the output we can determine that it is a null variable.
The second line is for the variable “y”; from the output, we can determine that it is not a null variable.
Example 2: Checking for other falsy values
The null value is known as a falsy value in JavaScript, and there are other falsy values in JavaScript. These falsy values include:
-
- NaN
- “” (an empty string)
- undefined
- false
- And a few more.
However, they cannot be detected as null, and thus if-else statements cannot determine these variables as null.
To demonstrate this, create a few variables with these falsy values with the following lines of code:
var b = "";
var c = NaN;
var d = false;
var e = 0;
After that, simply pass these variables one by one to the checkNull() function that we created in the previous example:
checkNull(b);
checkNull(c);
checkNull(d);
checkNull(e);
Executing the code will give the following output on the terminal:
All of these variables were considered to be non-null even though all belong to the same family which is “falsy values”.
Conclusion
In JavaScript, if-else statements can be used to determine whether a variable is a null variable or not. For this, we simply set the condition inside the if-else statement as (varName !== null), where varName is the variable identifier, we are checking. In this article, we created a function named checkNull() that determines whether the variable passed inside its argument is a null variable or not.