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.

4 Comments:

At 4:41 PM, Anonymous Nicholas 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.

 
At 7:19 AM, Blogger HiiFii Webservices said...

I wanted to show you some superb resourses on the net.
Learn to earn 90000$/Month
For which you may also see my Personal Website
Here.
and for a Personal Education Career Tools
free Study Database.
This site is for seeing the
Hifi Electronics.
And this is for
World Class Gadgets

 
At 6:04 PM, Blogger satxxkenn said...

Cool blog - Check out my site if you need help finding a good low interest credit card. Credit Cards

 

Post a Comment

<< Home