# no const for classic "for"

[JS](../../..) ⟩ [statement](../../../grammar/statement) ⟩ [declaration](../../../grammar/declare) ⟩ [const]() ⟩ no const for classic for-loop

{% hint style="danger" %}
[](<> "mention")&#x20;

* <mark style="color:green;">**can**</mark>**&#x20;**<mark style="color:yellow;">**be used**</mark> with [in](../../../grammar/statement/loop/for/in "mention") / [of](../../../grammar/statement/loop/for/of "mention") loop.
* <mark style="color:red;">**can't**</mark> <mark style="color:yellow;">**be used**</mark> with a <mark style="color:yellow;">**classic**</mark> [for](../../../grammar/statement/loop/for/for "mention") <mark style="color:yellow;">**loop**</mark>.&#x20;

👉 [no-for-loop](no-for-loop "mention"):exclamation:
{% endhint %}

{% tabs %}
{% tab title="💈範例" %}
* replit：[classic for-loop can't use const](https://replit.com/@pegasusroe/classic-for-loop-cant-use-const#index.js)
* 👉 [type](../../../err/type "mention") ⟩ [const-no-reassign](../../../err/type/const-no-reassign "mention")

```javascript
const { log } = console;

const array = [1,2,3];
const students = ['Joe', 'Jane', 'Jack'];

// ⭐️ for-in loop
//   ╭───╮ <------------------------- this is OK ✅
for (const index in students) {
    // this `const` behaves like:
    //
    //    // inside block scope
    //    const index = <next index in students>
    //
    log(`${index}: ${students[index]}`);
}

// ⭐️ for-of loop
//   ╭───╮ <------------------------- this is OK ✅
for (const value of array) {
    // this `const` behaves like:
    //
    //    // inside block scope
    //    const value = <next value of array>
    //
    log(value);
}

// ⭐️ classic for-loop❗
//
//   but this `const` behaves like: 
//
//       // in its own scope❗ (like function name scope)
//       // (inside for-loop but outside block scope)
//       // (between outer scope and inner block scope)
//
//       const i = 0;        // ⭐️ reassignment will fail❗
//
//  ╭─ for-loop init scope ─╮
//   ╭───╮ <------------------------- this is NOT OK ❌
for (const i = 0; i < 3; i++) {
    //                   ^^^
    // TypeError after the first iteration❗
    // (⛔ TypeError: Assignment to constant variable)
    log(i);
}

// output
// ---------------------
// 0: Joe
// 1: Jane
// 2: Jack
// 1
// 2
// 3
// 0 <----- ⭐️ first iteration (then fails)
// ⛔ TypeError: Assignment to constant variable.
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] [ydkjs-scope-and-closures-v.2](../../../../master/ref/book/you-dont-know-js-series-v.2/ydkjs-scope-and-closures-v.2 "mention") ⟩ Ch. 5 ⟩ [Constants?](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch5.md#constants)
{% endtab %}
{% endtabs %}
