Consider the following code.
const iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
console.log(('after for...of'), iterable); // [10, 20, 30] - no change
const iterable1 = [10, 20, 30];
for (let i = 0; i < iterable1.length; i++) {
iterable1[i] += 1;
console.log(iterable1[i]);
}
// 11
// 21
// 31
console.log(('after regular for...'), iterable1); // [11, 21, 31] - values changed
As you see and as was stated in the question, the values in the array didn't change after the for...of
loop, but did after the regular for
loop.
After reading this article on MDN about the for... of
I was led to believe that(at least in this particular context) it would be identical to the for
loop, but as you see, this has proven not to be the case. It is especially baffling for me since the article states that
It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
The article proceeds to state that you can reassign values of the iterable(in our case, an array) inside the block.
You can use
let
instead ofconst
too, if you reassign the variable inside the block.
It would seem to me that I lack some critical (maybe even trivial) insight into how the for...of
works, and I hope you could help me better understand what is going on.