Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `const` value changed inside of `for...in` and `for...of` loop?

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.

As per MDN The value of a constant cannot change through re-assignment, and it can't be redeclared, so inside of for...in and for...of how is working?

const data = ['A', 'B', 'C', 'D'];

//Here const key is changed
for (const key in data) {
  console.log('key ',key);
}

//Here const value is changed
for (const value of data) {
  console.log('value ',value);
}
like image 947
Narendra Jadhav Avatar asked Apr 06 '18 13:04

Narendra Jadhav


2 Answers

In for-of-loop those constans are being declared for every iteration (in independent scopes), whereas in a for-loop you're re-using the variable, so you won't be able to re-assign values after its declaration.

Example with for-loop

const data = ['A', 'B', 'C', 'D'];

for (const i = 0; i < data.length; i++) {
  console.log('value ',data[i]);
}
like image 160
Ele Avatar answered Oct 31 '22 20:10

Ele


The first three words of the material you quoted explains.

Constants are block-scoped

Each time you go around the for loop, you go to the top of a clean block. The first thing you do to it is to create a constant inside it.

like image 23
Quentin Avatar answered Oct 31 '22 20:10

Quentin