1

So I have some local javascript code that I'm executing with Node (v6.0.0). I noticed something weird after running into an error with javascript running out of memory in the memory heap; iteration variable scopes "following" into functions called in the loop. Consider this example;

function foo() {
  for (i = 0; i < 2; i++) {
    console.log(`i in foo():${i}`);
  }
}

function bar() {
  for (i = 0; i < 2; i++) {
    foo();
    console.log(`i in bar():${i}`);
  }
}

Coming from Java, I'd expect this to print

i in foo(): 0
i in foo(): 1
i in bar(): 0
i in foo(): 0
i in foo(): 1
i in bar(): 1

But what it actually prints is the following;

i in foo(): 0
i in foo(): 1
i in bar(): 2

And then exits. Is this intended behavior of Javascript? I'd expect the scope of the i variable not to continue into the called function normally.

Nyfiken Gul
  • 654
  • 4
  • 20

1 Answers1

2

In your code i is not defined anywhere so it will be defined in global scope. So initialize the variable in for loop for making a local variable.

function foo() {
  for (let i = 0; i < 2; i++) {
  //---^^^^^^^^^---------------
    console.log(`i in foo():${i}`);
  }
}

function bar() {
  for (let i = 0; i < 2; i++) {
    foo();
    console.log(`i in bar():${i}`);
  }
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 2
    Oh, I see, that explains it. Thanks. Haven't seen "let"s inside a for loop declaration before, but I'm still getting used to the transition. Cheers! – Nyfiken Gul Mar 12 '19 at 18:27
  • 3
    @NyfikenGul As you are starting up with js, try to write code in strict mode, it will save your time. :-) – amrender singh Mar 12 '19 at 18:28