Wednesday, April 06, 2005

Variable scoping gotchas

Phil points to this great bit by Scott Issacs about JavaScript variable scoping. I've seen hardcore programmers as well as JS newbies make the same simple mistake:

function Foo() {
  bar = 1;

You might assume bar is private to Foo, but you'd be mistaken. Variables declared without the var operator are global by default. The correct syntax is:

function Foo() {
  var bar = 1;

Check out Scott's weblog for more scripty goodness.


At 4:41 PM, Anonymous Anonymous said...

That's one of the most common mistakes new JavaScript developers make. However, the forgiving nature of JavaScript means that for most simple applications, you may never see a problem. If you end up writing hundreds of lines of JavaScript code, though, problems start to crop up pretty quickly.

You may also be interested to know that creating local variables instead of global variables (by mistake, of course) can speed up the execution of your JavaScript code.


Post a Comment

<< Home