Posts

Showing posts from July, 2010

JavaScript: Checking for undeclared and undefined variables

Up until now, the JavaScript I've written has typically been in pursuit of a bigger goal. This means that I worked around language quirks on the spot and moved on. I never stopped to consider the nitty gritty details of the language for commitment to long-term memory, because I wanted to get a working end product. Recently, someone asked me about the best way to check for undefined JavaScript variables. I found myself at a loss, which was alarming to me since doing these kinds of checks is immensely important, practical, and a frequent fact of everyday programming no matter what programming language you're using. The fact of the matter is that most of the time, I know where my variables are coming from. Something like this would work: var x; if (x) x.some_method(); else alert("we can't use x"); In the vast majority of cases where I had to perform a null check, I knew that the variable was declared somewhere because it was of my own maki