1

I have something similar to the following code in Javascript:

func1() {
    for(i = 2; i < 5; i ++) {
      console.log(i);
      func2(i);
    }
}

func2(x) {
    for(i = 100; i < 200; i ++) {
      do something
    }
}

Apparently the output for my this program is one single line with a 2, although it worked if I change the index name for one of the for loop from i to ii for example.

Is it an expected behavior in javascript that the i in the for loop in func1 actually changes to 100 after calling func2 the first time?

If this is true is there any way to get around this issue without naming each index differently? This is extremely annoying when there are a lot of function calls nested.

2
  • where is i declared? what is its scope? Commented Sep 8, 2017 at 5:17
  • i is global (and the same variable for both functions) in this code Commented Sep 8, 2017 at 5:19

1 Answer 1

2

You need to do like this,

func1() {
    for(var i = 2; i < 5; i ++) { // define i here
      console.log(i);
      func2(i);
    }
}

func2(x) {
    for(var i = 100; i < 200; i ++) { // define i here
      do something
    }
}

If you declare as global then it will have the recent value so as you need unique vale for each function , you should declare within function

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

2 Comments

Thank you so much!! I will accept the answer after the nine minute limit.
The OP didn't declare i at all, it becomes global only when the code is executed because it isn't declared. ;-)

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.