0

I have seen many examples where people have nested for loops and they change their increment variable (i,j,k).

for(var i=0;i<array.length;i++){
    for(var j=0;j<array.length;j++){
        for(var k=0;k<array.length;k++){

        }
    }
}

So my question is why doesn't calling a function from a for loop, that has a for loop inside it not cause a collision of the increment variables? Is it because of the function scope nature of javascript or is it colliding and I just haven't had a problem. Example:

for(var i=0;i<array.length;i++){
    callFunction()
}

function callFunction(){
    for(var i=0;i<arry.length;i++){
        console.log(i)
    }
}
hvchris
  • 86
  • 1
  • 8
  • 4
    Scope, the `i` variable inside the function has another scope, and is not the same as the one outside the function. – adeneo Mar 17 '13 at 05:07
  • This is a good read on the subject of scope and closures: http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/ – Aaron Blenkush Mar 17 '13 at 05:09
  • oddly enough I had a very complicated project that had to do many many nested loops of different arrays and objects because of it's dynamic nature, and my boss said, what do you know about closures, i think that could solve your problem of all these whacky variables you are creating, so I made one loop method that took an array and a custom function to fire off during each iteration in the loop and it just worked. after all my research I figured closure was my saving grace, but i wanted some more experience eyes on it. so your comment is very relevant! – hvchris Mar 17 '13 at 05:15

1 Answers1

4

I don't know why adeneo didn't make it an answer, but indeed it has to do with scope. Compare it to:

function first() {
  var i = 2;
  console.log(i);
}

function second() {
    var i = 3;
    console.log(i);
    first();
}

The i variable in each function is contained within the function, so the variables don't clash. If you had used global variables (i = 3 instead of var i = 3) then they would've clashed.

If you want some material on javascript and scope rules, check out this question or these links:

Community
  • 1
  • 1
Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123
  • 1
    An additional note is that forgetting to use "var" and thus accidentally creating or referencing a global variable is perhaps the most commonly made scope-related error in all of javascript. This aspect of js is subtle and scope can be tricky, so it pays to spend time getting as familiar as possible - like with the resources you linked! – BrianH Mar 17 '13 at 05:16