How do I determine if variable is undefined
or null
?
My code is as follows:
var EmpN
jQuery check element not null:
var dvElement = $('#dvElement');
if (dvElement.length > 0) {
// Do something
}
else{
// Else do something else
}
To test if a variable is null or undefined I use the below code.
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
You can only use second one: as it will check for both definition and declaration
You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code).
if (x === null || x === undefined) {
// Add your response code here, etc.
}
The foo == null
check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...
The explicit approach, when we are checking if a variable is undefined
or null
separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0
as both short and safe way to perform check for undefined
.
Using foo === undefined
is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined'
check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:
if (foo === void 0 || foo === null) { ... }
In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below.
if (variable === undefined){
}
if (variable === null){
}
if (variable === ''){
}
Check all conditions:
if(variable === undefined || variable === null || variable === ''){
}