Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
Attention :: people who don't understand the difference between a proposition let
, a constant const
and a variable var
should refrain themselves from commenting.
These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.
Suppose I need my variableName;
to carry an undefined
value, and therefore it has been declared in a manner such as var variableName;
which means it's already initialized; - How do I check if it's already declared?
Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?
We do it by using the most powerful JasvaScript operator, the in operator.:
"[variable||property]" in [context||root]
>> true||false
In times of AJAX peaking popularity I've written a method (later named) isNS() which is capable of determining if the namespace exists including deep tests for property names such as "Book1.chapter22.paragraph37" and a lot more.
But since it has been previously published and because of its great importance it deserves to be published in a separate thread I will not post it here but will provide keywords (javascript + isNS ) which will help you locate the source code, backed with all the necessary explanations.