2
I was reading the series You Don’t Know JS which says the following about let
declared in for
loops:
There’s a special behavior defined for
let
declarations used in the head of a for-loop. This behavior says that the variable will be declared not just Once for the loop, but each iteration. And, it will, helpfully, be initialized at each subsequent iteration with the value from the end of the Previous iteration.
Now, I tried that the other day:
var numeros = [4, 5, 6];
var n = [];
for (let l = n.length; l < numeros.length;) {
n.push(numeros[l] * 2);
}
// [8, 8, 8, 8, 8,...] loop infinito
However, this works as expected:
for (;n.length < numeros.length;) {
n.push(numeros[n.length] * 2);
}
// [8, 10, 12]
It is interesting what happens by mixing the two cases, because the l
does not change with each iteration:
I hoped that l
change in all cases, why is not what happens?
I’ll ask you then in a simple way, because the question has nothing to do with closure, but, yes the link has examples of such, what is your real doubt? is to know if the
let
of the variable is always redeclared in each passage in thefor
or what is the difference between the two forms? what you expect as an answer, because it’s very easy to say that I’ve gone out of focus, but the other answer has also gone out of focus and said that there are ways to do it differently is not the focus of the question.– novic
The question is the one that is above even, why the
let
is not redeclared at every iteration. I still don’t understand why. I suspect that, as you said, only the incrementing/decreasing field would change the value of what is declared there in the first expression, and then makes sense with the link example, because it uses the third expression of the for. However, I think that a more dedicated research into the specification of Ecma could bring greater clarification.– mjfneto
in my vision if you don’t care
closure
you want to know the difference between the twofor
of your question and this may be confused.– novic
though I understood, that your doubt is because the
n
increasing and you think that this value is being passed again tol
, and this will not happen, because the first only passes the initial value ... its increment is either done in the third parameter that is ideal or in the body of thefor
!– novic
Right. I think it’s reasonable. I’ll take a look at the specification.
– mjfneto
when a debug is done, for example it only passes on startup once. understood?
– novic
Yes, I get it. You’ve emphasized that very strongly.
– mjfneto