⛔no const for classic "for"
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.Last updated