Javascript: checking if variable exists

Recently I’ve learned that the best way to check if variable really exists in JavaScript is to call if (typeof somevar !== "undefined"). It seems to be most reliable as typeof always returns string and non-existing var is always “undefined”. Be aware that even if you declare variable with var somevar; it’s still undefined as it has no value assigned during declaration.

  1. by sobstel • February 2011 • blog archive