What's this?
- I'm studying this book.
- I'd not known it is ok that
const
is used in the "for of" loop.
What I learned
How to use const element in the for loop
Like this example, you can use const
when initializing for loop for array.
At first glance, you might think that there would be more than one value in const.
const l = [1, 2, 3]; for (const i of l) { console.log(i); } // => 1 // 2 // 3
But, in fact, JavaScript creates a new variable in the each iteration.
So you can use const
.
Note: Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case).
Note: Reassigning a variable does not change the original variable.
Stated above, each iteration creates a new variable, so you cannot change the value in the original array.
At most, only you can change is the variable you use in the iteration.
const L = [[1, 2], 3, 4]; for (let i of L) { i = 1000; } console.log(L); // => [ [ 1, 2 ], 3, 4 ]
Side note: You can use destructuring to assign multiple local variables
I learned a tip when reading document.
You can use desructuring to assing multiple variables. I think it can be used in many situation you use array in array.
const LL = [[1, 2], [3, 4], [5, 6]]; for (let [i, k] of LL) { console.log(i, k) } // => 1 2 // 3 4 // 5 6
Impression on Implementation
- I should notice the scope of the variable
- Readng the official document enables me to learn some new topics and tips.