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.
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?
I use two different ways depending on the object.
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
Sometimes I do not want to evaluate an empty string as falsey, so then I use this case
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.
In many cases, using:
if (elem) { // or !elem
will do the job for you!... this will check these below cases:
undefined
''
So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' '
one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array []
and empty object {}
are always true.
I create the image below to show a quick brief of the answer:
If variable was not defined at all, you can check this without break code execution using try-catch block as follows (you don't need to use strict
mode)
try{
notDefinedVariable;
} catch(e) {
console.log('detected: variable not exists');
}
console.log('but the code is still executed');
notDefinedVariable; // without try-catch wrapper code stops here
console.log('code execution stops. You will NOT see this message on console');
BONUS: (referring to other answers) Why ===
is more clear than ==
(source)
I'm surprised this wasn't mentioned yet...
here are a couple of additional variations using this['var_name']
the benefit of using this method that it can be used before a variable is defined.
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!