How to Check if a Javascript Variable Is undefined or null?
There are a few ways to check if a JavaScript variable is undefined or null:
- Using the typeof operator:
if(typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
- Using the triple-equal (===) operator:
if(variable === undefined || variable === null) {
// variable is undefined or null
}
- Using the ! (not) operator:
if(!variable) {
// variable is undefined, null, false, 0, NaN, or an empty string
}
Note that the third method checks for other falsy values in addition to undefined and null. If you only want to check for undefined and null, use one of the first two methods.