11

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);
}
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
  • possible duplicate of [scope rules of variables in for, for-in and for-of loops](https://stackoverflow.com/q/49573227/1048572) – Bergi Apr 06 '18 at 14:12

3 Answers3

9

Every iteration of a loop has its own block scope.

 for(let i = 0; i < 10; i++)
   setTimeout(() => console.log(i), 1);

That creates 10 seperate scopes, thats why it logs 10 different numbers. Therefore you can also declare constants in these different scopes.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • JavaScript `const` is the least constant `const` of any language I've seen that uses a term like that. It's not a compile-time constant like in C# or C++. – JamesFaix Apr 06 '18 at 13:47
  • @james yes, js is an interpreted language. – Jonas Wilms Apr 06 '18 at 13:48
  • 1
    @Jonas That's not really an argument; even JS has a compilation step, and even without a compilation step constants *could* be immutable. – deceze Apr 06 '18 at 13:52
  • 1
    @deceze i think it is. Javascript is very dynamic in comparison to C++ / C# and thats because it is interpreted. A compiled language can't be that dynamic (without much overhead) – Jonas Wilms Apr 06 '18 at 13:54
  • 2
    PHP demonstrates that it's possible to be interpreted and have constant constants. As I'm sure other languages do too. These attributes are unrelated. – deceze Apr 06 '18 at 13:56
5

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

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]);
}
Ele
  • 33,468
  • 7
  • 37
  • 75