I have seen people using const on for of loops, i admit why it doesnt work in the case of for loops but, does for of loop has the same case as that of for loops.
can you share your knowledge why const works on for of loops in javascript
I have seen people using const on for of loops, i admit why it doesnt work in the case of for loops but, does for of loop has the same case as that of for loops.
can you share your knowledge why const works on for of loops in javascript
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (7)
You didn't specify where in the loop, but I'm going to assume the obvious :)
in a
forloop, 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
iwere aconst, it would throw an error at the end of the first iteration, wheni++was executed.on
for ... ofloops, 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
valuevariable will only exist until the end of each iteration.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.
Thanks Guilherme
For exemple with a for loop
for (const i = 0; i < 100; i++) {
// ....
}
You can't use
constbecauseI++will incrementi.But
iis a constant. A constant can't change. So you have to useletI don't know all details for
for ofloop, just it uses Iterator. I found a good article about loops details : exploringjs.com/es6/ch_for-of.htmlThanks 4 investing the time for helping me out amiceli
Genuinely good question!