This solution to check the existence of variable
Read AlsoVariable Scope
We can use typeof operator to check the variable is defined or not.
You can use this code:
- The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
typeof nullwill be return as
- To avoid the mistake of initializing a variable to
null, we can use like this:
Read AlsoScope Variable in C++.
The following example has simpler semantics, which makes it easier to describe code's behavior.
window is a name for the global object
This solution gives if a variable exists and has been initialized.
It is most commonly used in combination with a ternary operator to set a default as certain variable has not been initialized :