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.