JavaScript checking whether a variable exists

JavaScript provides no good way to check if a variable exists.  If you try to use one that doesn't, you get a big fat error.  I've seen some people use:

if (myVar == undefined)

But this only works if the variable has been declared, but wasn't set to a value.  Sometimes, you don't know if the variable was even declared.

Here's some code that solves that: 

try {
      if (myVar) {}
} catch (err) {
      var myVar = "";
}

You can do whatever you want in the catch block. Initializing the variable, as I show, is a good way to avoid errors you would've gotten if the variable didn't exist.

  1. Anonymous (not verified)
    Sun, 08/31/2008 - 7:58am
    Lil bit late, but in global scope you may use window.myVar to check if undefined...
  2. kelvinv (not verified)
    Wed, 01/07/2009 - 9:03pm
    that is a great solution, another method can be if (typeof myVar == "undefined") also work too ^^
  3. Anonymous (not verified)
    Tue, 09/22/2009 - 8:58pm
    No, "typeof..." doesn't really work. I tried both methods and only the try/catch really worked at all due to the exception created when the variable does not exist.

    Cheers!

  4. Anonymous (not verified)
    Wed, 03/18/2009 - 8:07am
    Thanks for this, very useful!