Nasty Javascript

Implied Globals

foo="I'm a global foo."
bar="I'm a global bar."

function xyz() {
  var foo="I'm a local foo"
  bar = "I'm a local bar" // the implied global
}
  

This can make it really hard to see where your variables might be getting modified, for example:

function showextrafoo1() { alert(extrafoo1) };

   Right now nothing shows, as 'extrafoo1' is still undefined

<input type="button" onclick="extrafoo1='yo, yo'" value="create extrafoo1">

If it gets defined in an event handler...

It is now defined globally!

Thus, always use var:

<input type="button" onclick="var extrafoo2='ho ho'" value="create extrafoo2">

Now extrafoo2 does not materialize in the global scope to create potential havoc...







Back to Tutorials