The fact of the matter is that most of the time, I know where my variables are coming from. Something like this would work:
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 making.
What if you're counting on something having been declared somewhere else and being there? Let's try this.
alert("we can't use y");
After much experimenting and looking around the web, here's my definitive, reliable, robust, cross-browser way to perform this kind of check:
if (typeof(z) != "undefined")
alert("we can't use z");
It also works for when you're the one in charge of declaring a variable, too.
if (typeof(w) != "undefined")
alert("we can't use w");
So that fixes our problem. But look closer, and you may have a couple of nagging questions.
Why in the world would you be referencing a variable you didn't declare? If we only ever had to deal our own code, we should always know where the variables that we're using are coming from. But that is not the case for many of us; we rely on using others' code, third-party modules, or frameworks all the time.
You could also find yourself in a situation where you're expecting some object to be initialized because it's an external library. If it's loaded over the network, and loaded separately from the rest of your code, you'll want to recover gracefully if it's not available for some reason (like the remote server is down).
Why do we have to compare to the string "undefined" instead of the keyword? Because typeof() always returns a string.
console.log(typeof(j)); // "undefined"
console.log(typeof(typeof(j))); // "string"
What if it could also be null in some cases? Then you add a check for null. I've limited the check to checking for "undefined" to keep the explanation focused, but yes, in reality you'll want to do an additional check.
if (typeof(k) != "undefined" && k)
alert("we can't use k");
The check for null is pretty straightforward; it's "undefined" that trips us up. Note that, as written, this code will only proceed to check for the null condition if k has been defined. This is because of short-circuiting: if the first condition is true, there's no need to evaluate the rest of the other parts of the conditions.
We also saw that typeof() will always return a string, which means you need to compare its result to a string when you're running a conditional test.