Categories:

Determining the existence of a variable

As we learn about JavaScript, a question almost invariably comes up along the way: "Is there a way to determine whether a particular variable exists or not in a script?" In other words, can I ask JavaScript whether, say, "x", is defined in a script, and do something different, depending on the result? You may think the solution looks something like this:

if (x)
//do this
else
//do that

The above code is incorrect, and not only does not successfully detect whether x exists or not, but generates an error in the event that it doesn't. You see, you can't ask JavaScript about anything that isn't even defined yet (in the event that "x" isn't defined) without it throwing a tantrum. But there is a small portal to the world of the unknown in JavaScript, and that is the typeof operator.