I came across a problem with JavaScript earlier trying to see if a variable actually exists or not. For example…
if (x) {
// x exists.
} else {
// x doesn't exist.
}
Unfortunately this causes an error if x hasn’t been defined, eg…
var x = "robs test";
The solution came after a read of JavaScript: The Definitive Guide chapter 4. It explains about the Global Object, and that all global variables are located there. For client side JavaScript this is the Window object. So to see if x
has been defined we need to check window.x
, eg…
if (window.x) {
// x exists.
} else {
// x doesn't exist.
}
This means if I forget to define x
it will default to the block of code saying that x doesn’t exist. Of course, I shouldn’t really be in a situation where variables haven’t been defined, but sanity checking is always a good idea, especially with development code.