arrays are iterated "live"❗️

JSsyntaxfor loopsfor-of ⟩ arrays are iterated "live"❗️

changes made during the iteration may affect the outcome of the iteration.

const _Number = require('./ext/Number_ext');    // for `num.isEven`

let [arr1, arr2, arr3] = [
    [1, 2, 3],
    [1, 2, 3],
    [1, 2, 3],
];

let [count1, count2, count3] = [0, 0, 0];

// ---------------------------------
// ⭐ arrays are iterated "live"❗
// ---------------------------------

// ⭐ 1. append elements
for (const value of arr1) {
    log(value);                              // 1,1,1,1,2,3❗
    if (count1 < 3) arr1.unshift(count1);    // ⭐ prepend element
    count1++;
}
// ┌─── next
// 1, 2, 3
//    ┌─── next
// 0, 1, 2, 3
//       ┌─── next
// 1, 0, 1, 2, 3
//          ┌─── next
// 2, 1, 0, 1, 2, 3
//             ┌─── next
// 2, 1, 0, 1, 2, 3
//                ┌─── next
// 2, 1, 0, 1, 2, 3
arr1,    // [ 2, 1, 0, 1, 2, 3 ]❗

// ⭐ 2. prepend/append
for (const value of arr2) {
    log(value);                     // 1,1,2,2,3,1❗
    if (count2 < 3) count2.isEven
        ? arr2.unshift(count2)      // ⭐ prepend new element
        : arr2.push(count2);        // ⭐ append new element
    count2++;
}
// ┌─── next
// 1, 2, 3
//    ┌─── next
// 0, 1, 2, 3
//       ┌─── next
// 0, 1, 2, 3, 1
//          ┌─── next
// 2, 0, 1, 2, 3, 1
//             ┌─── next
// 2, 0, 1, 2, 3, 1
//                ┌─── next        // iteration ended
// 2, 0, 1, 2, 3, 1
arr2,    // [ 2, 0, 1, 2, 3, 1 ]❗

// ⭐ 3. shift (remove first) element
for (const value of arr3) {
    log(`value = ${value}`);       // 1,3❗
    if (count3 < 3) log(`shifted value: ${arr3.shift()}`);    // ⭐ remove first element
    count3++;
}
// ┌─── next
// 1, 2, 3                         // iteration started (1 will be removed)
//    ┌─── next                    
// 2, 3                            // iteration ended (2 will be removed)
// 3,                              // (2 removed)  
arr3,    // [ 3 ]❗

Last updated