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,783 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