Determine if a variable is null or undefined in JavaScript
This post will discuss how to check if a variable is null or undefined in JavaScript.
There are 7 falsy values in JavaScript – false, 0, 0n, '', null, undefined and NaN. A nullish value consists of either null or undefined. This post will provide several alternatives to check for nullish values in JavaScript.
To check for null variables, you can use a strict equality operator (===) to compare the variable with null. This is demonstrated below, where the boolean expression evaluates to true for only for null and evaluates to false for other falsy values.
|
1 2 3 4 |
var x = null; if (x === null) { console.log("variable is null"); } |
Similarly, to check specifically for undefined variables, you can use the strict equality operator (===).
|
1 2 3 4 |
var x; if (x === undefined) { console.log("variable is undefined"); } |
To check if a variable is either null or undefined, you can merge the above conditions. The following code demonstrates this, where the conditional statement is satisfied only for null or undefined values.
|
1 2 3 4 |
var x = null; if (x === undefined || x === null) { console.log("Variable is either null or undefined"); } |
Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator (==). This would work since null == undefined is true in JavaScript.
|
1 2 3 4 |
var x = undefined; if (x == null) { console.log("Variable is either null or undefined"); } |
That’s all about checking if a variable is null or undefined in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)