You didn't specify where in the loop, but I'm going to assume the obvious :)
in a for loop, you are creating a variable to count the iterations, and this variable is going to change, thus it can't be a constant value.
for(leti=0;i<5;i++){}
if i were a const, it would throw an error at the end of the first iteration, when i++ was executed.
on for ... of loops, you create a variable to keep the value of the iterable (list) to use during that iteration of the loop... when it loops over, a new variable will be created, with the same name and different value. it does not try to reassign, it just releases the variable that was used in the last iteration and creates a whole new one.
for(constvalueof[1,2,3,4]){}
the value variable will only exist until the end of each iteration.
A new lexical scope is created for each iteration and each lexical closure has its own copy of i.
for ([initialization]; [condition]; [final-expression])
statement
initialization initializes the loop environment‡.
final-expression runs at the beginning of each iteration except the first one.
before condition is checked a new lexical environment is created for the iteration and the current loop environment (i) is copied into that then condition is checked. Continue if satisfied, break if not.
statement is executed.
the lexical environment is copied back to the loop environment.
You didn't specify where in the loop, but I'm going to assume the obvious :)
in a
for
loop, you are creating a variable to count the iterations, and this variable is going to change, thus it can't be a constant value.if
i
were aconst
, it would throw an error at the end of the first iteration, wheni++
was executed.on
for ... of
loops, you create a variable to keep the value of the iterable (list) to use during that iteration of the loop... when it loops over, a new variable will be created, with the same name and different value. it does not try to reassign, it just releases the variable that was used in the last iteration and creates a whole new one.the
value
variable will only exist until the end of each iteration.Thanks Guilherme
The
let
in the modernfor
loop is actually a bit disingenuous.The early version of the
for
loop worked like this:Unintuitive but correct as by the time
console.log()
executedi
was2
.Typically the intention is this:
The
let
version automatically works that wayA new lexical scope is created for each iteration and each lexical closure has its own copy of
i
.initialization
initializes the loop environment‡.final-expression
runs at the beginning of each iteration except the first one.condition
is checked a new lexical environment is created for the iteration and the current loop environment (i
) is copied into that thencondition
is checked. Continue if satisfied, break if not.statement
is executed.‡
initialization
has its own lexical scope.