Let Vs Var: Scopes In For-loop
Solution 1:
From your example, the environment for the "lexical declaration" let i
is being created every iteration. However, the for
loop uses the previous environment in order to create the next environment. So when the increment occurs it begins where it left off. Otherwise using let
to declare i
would create an infinite loop (i.e. i
would always be <10
).
How it works:
In the for loop body evaluation, the step after 'test' and 'result' is CreatePerIterationEnvironment(perIterationBindings) which declares a new environment and initializes all the bindings to their last known value: thisIterationEnv.InitializeBinding(bn, lastValue)
. Once complete the new environment is set as the current environment and the 'increment' step begins.
Definition:
InitializeBinding(N,V) Set the value of an already existing but uninitialized binding in an Environment Record. The String value N is the text of the bound name. V is the value for the binding and is a value of any ECMAScript language type.
Solution 2:
The first one, the wrong(unexpected) result is just because closures have access to the updated values of the outer function’s variables(finally the variable 'i' in closures is 10);
The second one, use let
to declare variable i
to mark it as a block variable
which means the closures get the immediate i
(like IIFE).
Post a Comment for "Let Vs Var: Scopes In For-loop"