One of the easiest ways we can use JavaScript to check if a variable exists is with exception handling using a try-catch statement.
try{
console.log(some-variable);
} catch(err) {
console.log("variable doesn't exist");
}
#Output:
variable doesn't exist
This way will make sure that if you try to check if a variable exists that has not been initialized, you can handle the error that will be returned so that it does not break your program.
Another easy way that we can use JavaScript to check if a variable exists is by using the JavaScript typeof Operator in an if conditional statement.
if ( typeof someVariable !== "undefined" ){
//The variable DOES exist
}
In the code above, someVariable is the variable we want to check to see if it exists. typeof someVariable will return “undefined” if the variable does not exist, and therefore the conditional statement will be false.
Now let’s show some examples of this code in use:
var variable1 = {name:'tom', age:25};
var variable2 = [1,2,3,4];
var variable3;
var variable5 = undefined;
var variable6 = {};
if ( typeof variable1 !== "undefined" ){
console.log("variable exist");
} else {
console.log("variable doesn't exist");
}
if ( typeof variable2 !== "undefined" ){
console.log("variable exist");
} else {
console.log("variable doesn't exist");
}
if ( typeof variable3 !== "undefined" ){
console.log("variable exist");
} else {
console.log("variable doesn't exist");
}
if ( typeof variable4 !== "undefined" ){
console.log("variable exist");
} else {
console.log("variable doesn't exist");
}
if ( typeof variable5 !== "undefined" ){
console.log("variable exist");
} else {
console.log("variable doesn't exist");
}
if ( typeof variable6 !== "undefined" ){
console.log("variable exist");
} else {
console.log("variable doesn't exist");
}
#Output:
variable exist
variable exist
variable doesn't exist
variable doesn't exist
variable doesn't exist
variable exist
Hopefully this article has been useful for you to learn how to use JavaScript to check if a variable exists.
Leave a Reply