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.
"final-expression runs at the beginning of each iteration except the first one. "
mdn says: final-expression (called afterthought in their docs) evaluates at the end of each loop iteration not at the beginning of each iteration.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The
letin the modernforloop is actually a bit disingenuous.The early version of the
forloop worked like this:Unintuitive but correct as by the time
console.log()executediwas2.Typically the intention is this:
The
letversion automatically works that wayA new lexical scope is created for each iteration and each lexical closure has its own copy of
i.initializationinitializes the loop environment‡.final-expressionruns at the beginning of each iteration except the first one.conditionis checked a new lexical environment is created for the iteration and the current loop environment (i) is copied into that thenconditionis checked. Continue if satisfied, break if not.statementis executed.‡
initializationhas its own lexical scope."final-expression runs at the beginning of each iteration except the first one. "
mdn says: final-expression (called afterthought in their docs) evaluates at the end of each loop iteration not at the beginning of each iteration.