Reputation: 894
If I declare variable like this,
let variable;
How to check if the variable is declared?
(If it is initilized, I will do this way..)
if (typeof variable !== 'undefined') { }
Upvotes: 0
Views: 680
Reputation: 122
You can catch ReferenceError to check if the variable is declared or not.
var declared = true;
try{
theVariable;
}
catch(e) {
if(e.name == "ReferenceError") {
declared = false;
}
}
Upvotes: 3
Reputation: 1197
A variable that is not declared will produce a ReferenceError, so you need a simple try catch:
try {
if (typeof variable !== 'undefined') { }
} catch(error) {
//Handle nondeclared
}
Upvotes: 1