โ›”no const for classic "for"

JS โŸฉ statement โŸฉ declaration โŸฉ const โŸฉ no const for classic for-loop

const

  • can be used with for-in / for-of loop.

  • can't be used with a classic for loop.

๐Ÿ‘‰ 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