Method 3Using the typeof Operator
Using the typeof operator, JavaScript checks if a variable is not null by verifying typeof variable !== ‘undefined’ && variable !== null. This approach ensures the variable exists and is not explicitly set to null, promoting reliable code execution.
Example: In this example we are using typeof operator with !== ‘undefined’ and !== null checks if a variable is not null in JavaScript. Output “Variable is not null” if true, else “Variable is null”.
// Case 1: Variable is not null
let variable = "Hello";
if (typeof variable !== 'undefined' && variable !== null) {
console.log("Variable is not null");
} else {
console.log("Variable is null");
}
// Case 2: Variable is null
variable = null;
if (typeof variable !== 'undefined' && variable !== null) {
console.log("Variable is not null");
} else {
console.log("Variable is null");
}
Output
Variable is not null Variable is null
How to check if a Variable Is Not Null in JavaScript ?
Our focus lies on understanding how to verify if a variable is not null in JavaScript. We’ll explore several methods to tackle this issue effectively.
These are the following ways to solve this problem:
Table of Content
- Using if else
- Using Lodash _.isNull() Method
- Using the typeof Operator:
Contact Us