Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

Chad Dugas
PLUS
Chad Dugas
Courses Plus Student 13,304 Points

What is the scope of a variable declared in a for loop?

If you declare and define a variable (i) inside a for loop, what is its scope? Ex:

    for ( var i = 0; i <= 9; i++) {
      // some commands
    }

Can I reuse I later in the program? If so, does it need to be declared with var again next time I use it?

2 Answers

Petros Sordinas
Petros Sordinas
16,181 Points

Hi Chad,

It is local to the function you are executing the for loop.

kevinardo
seal-mask
.a{fill-rule:evenodd;}techdegree
kevinardo
Treehouse Project Reviewer

If it is not defined within a function, then it is attached to the global scope. If you use it within the same scope you can declare the var i = 0; at the top of the function like so:

     var i;
     for (i = 0; i <= 9; i++) {
     // some commands
     }
     for (i = 2; i < 10; i++) {
     // some commands
     }

And another good practice is to do it like this: Continue through the alphabet.

     for (var i = 0; i <= 9; i++) {
     // some commands
     }
     for (var j = 2; j < 10; j++) {
     // some commands
     }

Hope it helps :)