JavaScript check if variable exists (is defined/initialized)
Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
Solution 1:
You want the typeof
operator. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
Solution 2:
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?
Solution 3:
In many cases, using:
if (elem) { // or !elem
will do the job for you!... this will check these below cases:
-
undefined: if the value is not defined and it's
undefined
- null: if it's null, for example, if a DOM element not exists...
-
empty string:
''
- 0: number zero
- NaN: not a number
- false
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: