Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
In the majority of cases you would use:
elem != null
Unlike a simple if (elem)
, it allows 0
, false
, NaN
and ''
, but rejects null
or undefined
, making it a good, general test for the presence of an argument, or property of an object.
The other checks are not incorrect either, they just have different uses:
if (elem)
: can be used if elem
is guaranteed to be an object, or if false
, 0
, etc. are considered "default" values (hence equivalent to undefined
or null
).
typeof elem == 'undefined'
can be used in cases where a specified null
has a distinct meaning to an uninitialised variable or property.
elem
is not declared (i.e. no var
statement, not a property of window
, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.Also useful is a strict comparison against undefined
:
if (elem === undefined) ...
However, because the global undefined
can be overridden with another value, it is best to declare the variable undefined
in the current scope before using it:
var undefined; // really undefined
if (elem === undefined) ...
Or:
(function (undefined) {
if (elem === undefined) ...
})();
A secondary advantage of this method is that JS minifiers can reduce the undefined
variable to a single character, saving you a few bytes every time.