You want the typeof operator. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
The typeof operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison === instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
How to Check if a Variable Exists and is Initialized in JavaScript - LambdaTest Community
How could I check if a variable has been declared?
How to test if variable exists inside in an object within an array within an object within an array - JavaScript - SitePoint Forums | Web Development & Design Community
Checking if a variable exists with strict_variables set
If a variable is declared but no value has been assigned to it, then its type would be "undefined." The same type would be assigned to variables that haven't been declared. In that case, how would we check if a variable has been declared?