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 Simplify Repetitive Tasks with Loops For Loops

So is the for loop variable 'i' a global variable?

Dave mentions that using i and j is very commonly used with developers, but from my understanding (I think) loop variables are global variables. So therefore I would assume you can only use i/j name once in your editor but what happens if you want to use for loop again? Or do you just simply give it a different name.

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

Well, it can be, usually it is defined locally on the for statement.

Show some code of a loop you are questioning.

Check out some documentation should help your understanding - https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code

1 Answer

Daniel Yalg
Daniel Yalg
5,211 Points

Not super sure if this is what you mean. But!

for (var i = 0; i < 10; i++) {
    console.log(i);
}

In the above example 'i' is defined as a global variable yeah. However the loop will fully complete before moving past it. If you wanted to reuse the same loop elsewhere and reuse the 'i' variable it will just be reset to 0 when you redefine your loop later on. So nothing conflicts - it just overrides the global variable.

yes thats what i was asking. so you can use the 'i' as many time just as long as you redefine it. this was causing me some confusion. thanks for the answer