SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simple: check if variable exists

    I am trying to find out how to check if a variable exists or not to prevent an error if you use it when it's not defined.

    This is what I thought would work:
    Code:
    if (typeof varName === 'undefined') {}
    .. But I get a 'could not get the type property' error in IE6 and decent browsers still say the variable isn't defined.

    I'm pretty certain for an object you can just do:
    Code:
    if(object) {
    
    }
    ...but not with vars.

    So what is the best (all browser) way to check if a variable is defined?

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,192
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    The above code you posted should work fine in all browsers as it's been standard in the ECMA JavaScript spec since the IE6 and probably even before then, there is nothing to suggest the above wouldn't work.

  3. #3
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorted, thanks.

    Browser was caching my old JS file.

    Thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •