Checking if a variable is defined in JavaScript

In short, do not use "if(myvariable){ ... }" to check whether a variable is defined in JavaScript, because if it is not, the browser will return with an error and stop executing the script. The typeof operator can be used instead: "if(typeof(myvariable)!=='undefined'){ ... }".

According to this article, checking "window.myvariable" might be necessary, although the tests I've done do not show that "x" and "window.x" would behave differently.

Popular Posts