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.

2 Comments:

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.

 
At 7:13 AM, Blogger Global Names said...

Looks good your blog!.
I am sure that your blog page looks great to me which mean looking crowded so, My site - open event during one month domain registration information.
http://www.globalnames.com You better check it out some time.

 

Post a Comment

<< Home