1

Can anybody explain to me how this casue an infinite loop? I got this from an example of a javascript book.

The code is as follows:

function foo() {
  function bar(a) {
    i = 3; // changing the `i` in the enclosing scope's for-loop
    console.log( a + i );
  }
  for (var i=0; i<10; i++) {
    bar( i * 2 ); // oops, inifinite loop ahead!
  }
}
foo();
1
  • Well, you change i variable so you never reach the terminal condition i<10. Which part of this is unclear? Commented Mar 20, 2019 at 11:56

1 Answer 1

1

The problem is, that you're changing i from the for-loop inside your bar function

i = 3;

That means outside of bar it can't reach the condition i < 10.

So the calls of bar would be like:

  1. bar(0 * 2); then i = 3; then console.log(0 + 3); then i++
  2. bar(4 * 2); then i = 3; then console.log(8 + 3); then i++
  3. bar(4 * 2); then i = 3; then console.log(8 + 3); then i++
  4. and so on... i will stay smaller than 10

You should change your code to avoid the set of i = 3;, which is the root of your problem.

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

5 Comments

Wow. Thanks so much! Understood it instantly when u explain like this. I misunderstood this as I thought var i=0; i<10; i++ is in its own scope. Hence, the i = 3; would not cause it to change value. Thanks so much!
If it would be in its own scope the call of i = 3; would lead to an undefined error since you never introduced i before.
Oh right. Yet another learning point. Thanks so much! Thanks for bothering to explain such a simple question!
Always happy to help!
@BreakBB "the call of i = 3; would lead to an undefined error" - correction, that would create a global unless you are in strict mode - in that case, assigning to an undeclared variable throws a RefenceError instead of making an implied global.

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.