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)
    }
}
3
  • 4
    Scope, the i variable inside the function has another scope, and is not the same as the one outside the function. Commented Mar 17, 2013 at 5:07
  • This is a good read on the subject of scope and closures: robertnyman.com/2008/10/09/… Commented Mar 17, 2013 at 5: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! Commented Mar 17, 2013 at 5:15

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.