Javascript, scope fun with the for loop

I thought I’d share a bit of JavaScript or a little Got-Me, consider the following;

function A()
{
  for (index = 0; index < 10; index++)
  {
       alert(index);
       B();
       alert(index);
  }
  alert(‘finish’);
}

function B()
{
  for (index = 0; index < 10; index++)
  {
       // do nothing
  }
}


I ran this on Firefox/Safari and got….

0,9, finish
I was surprised on two counts, 1. Why didn’t the for loop work? 2. Why the shared scope? Anyway assuming I had accidentally created a global I corrected it and it worked as expected…

for (var index = 0; index < 10; index++)

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s