[Solved-5 Solutions] JavaScript check if variable exists (is defined/initialized) - javascript Tutorial
Problem:
How to check if a variable exists or defined in JavaScript ?
Solution 1:
This solution to check the existence of variable
Solution 2:
We can use typeof operator to check the variable is defined or not.
Solution 3:
You can use this code:
- The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
-
Note that
typeof null
will be return as"object"
. - To avoid the mistake of initializing a variable to
null
, we can use like this:
Solution 4:
In JavaScript, a variable can be defined, but hold the value undefined
.
The following example has simpler semantics, which makes it easier to describe code's behavior.
Where window
is a name for the global object
Solution 5:
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 :