JavaScript check if variable exists (is defined/initialized)

JavaScript check if variable exists (is defined/initialized)

You want the typeof operator. Specifically:

if (typeof variable !== undefined) {
    // the variable is defined

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, doesnt 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?

JavaScript check if variable exists (is defined/initialized)

In many cases, using:

if (elem) { // or !elem

will do the job for you!… this will check these below cases:

  1. undefined: if the value is not defined and its undefined
  2. null: if its null, for example, if a DOM element not exists…
  3. empty string:
  4. 0: number zero
  5. NaN: not a number
  6. false

So it will cover off kind of all cases, but there are always weird cases which wed 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:


Leave a Reply

Your email address will not be published.