I remember variables are function scoped in Javascript. But, how is the behavior if I redefine the local variable in a loop. One common use case is nested loops.
In the below code, if I change j to i, the outer for loop terminates after one iteration as the value of i in outer scope is same as inner for loop. Since I use var, I was expecting (similar to other language) it is redefined inside inner fo loop. Does this mean in JS, there is no way to redeclare and use local variable within function scope.
for (var i = 0, len = x.length; i < len; i++) {
...
for (var j = 0, len = y.length; j < len; j++) {
...
}
}
As you said, JavaScript only has function scope. Variable declarations are hoisted to the top of the scope in which they are declared. Your example is interpreted like this:
As for this part:
If you replace
jwithi, then after the first iteration of the inner loop,iwill bey.length - 1, and the outer loop will either continue or stop, depending on the difference betweenx.lengthandy.length.If you’re interested in the real explanation of the internal workings, the ECMAScript spec (Declaration Binding Instantiation) covers it in detail. To summarise, every time control enters a new execution context, the following happens (a lot more than this happens, but this is part of it):
This means that if you declare a variable more than once per execution context, it will effectively be ignored.