How to Check if a Variable is Not NULL in JavaScript
In JavaScript, you often need to check if a variable is not null
. This is a common task when you want to ensure that a variable has a meaningful value before proceeding with your code. Here’s how you can do it:
Basic Check for null
To check if a variable is not null
, you can use a simple !==
(strict inequality) comparison:
if (variable !== null) {
// variable is not null
}
Check for Both null
and undefined
Sometimes, you might want to check if a variable is neither null
nor undefined
. You can use the !=
(loose inequality) comparison for this purpose:
if (variable != null) {
// variable is not null and not undefined
}
Note that !=
will return true
for both null
and undefined
, which is usually desirable in cases where you want to handle both cases.
Using Logical Operators
For more complex conditions, you might combine checks using logical operators. For example, if you want to ensure a variable is not null
and also not an empty string:
if (variable !== null && variable !== "") {
// variable is not null and not an empty string
}
Example
Here’s a complete example showing how to check if a variable is not null
:
function checkVariable(variable) {
if (variable !== null) {
console.log("The variable is not null.");
} else {
console.log("The variable is null.");
}
}
let myVar = "Hello";
checkVariable(myVar); // Output: The variable is not null.
myVar = null;
checkVariable(myVar); // Output: The variable is null.
Summary
- Use
variable !== null
to check if a variable is notnull
. - Use
variable != null
to check if a variable is neithernull
norundefined
. - Combine conditions with logical operators if needed to handle more complex cases.
Feel free to adapt these methods to fit the needs of your specific application!