Sub topic 3
Iterating Values with for...of
This chapter assumes you know the classic for loop, arrow functions, and basic promises. It covers modern iteration and some patterns for cleaner control flow.
for...of and for...in
for...of loops over the values of any iterable: arrays, strings, Maps, and Sets. for...in loops over an object's enumerable property keys, and it always gives them to you as strings.
const letters = ["a", "b"];
for (const index in letters) {
console.log(index, typeof index); // "0" string, "1" string
}
for (const letter of letters) {
console.log(letter); // "a", "b"
}let vs var in Loops
let creates a new binding on every iteration. var has one binding for the whole function, so every closure created in the loop sees the same final value.
const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
console.log(withVar.map((f) => f())); // [3, 3, 3]
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withLet.map((f) => f())); // [0, 1, 2]Array Methods
Array methods replace common loop patterns. filter keeps the matching items, map transforms each item, and some and every stop as soon as they know the answer.
const nums = [1, 2, 3, 4];
console.log(nums.filter((n) => n % 2 === 0)); // [2, 4]
console.log(nums.map((n) => n * 2)); // [2, 4, 6, 8]
console.log(nums.some((n) => n > 3)); // true
console.log(nums.every((n) => n > 0)); // trueAwaiting Inside Loops
If you use await inside for...of, each task finishes before the next one starts. Promise.all with map starts all the tasks at once. Don't use await inside forEach, because forEach ignores the promises its callback returns.
const delay = (ms) => new Promise((r) => setTimeout(() => r(ms), ms));
async function sequential() {
for (const ms of [30, 10]) console.log(await delay(ms)); // 30, then 10
}
async function concurrent() {
console.log(await Promise.all([30, 10].map(delay))); // [30, 10]
}
sequential().then(concurrent);Guard Clauses and Lookup Tables
A guard clause returns early when it hits a special case, which keeps the main logic from nesting. A lookup table is an object that maps keys to results. Combined with a ?? fallback, it can replace a switch.
const shippingRates = { standard: 5, express: 15, overnight: 30 };
function shippingCost(order) {
if (!order) return 0;
if (order.total >= 100) return 0;
return shippingRates[order.method] ?? shippingRates.standard;
}
console.log(shippingCost({ total: 40, method: "express" })); // 15
console.log(shippingCost({ total: 40, method: "drone" })); // 5Exercise
You need to fetch five independent URLs and keep all the results. Should you use await inside for...of, or Promise.all with map? Why?
Show answer
Use Promise.all with map. The fetches don't depend on each other, so they can run at the same time. Awaiting inside for...of would run them one after another and add up all the wait times.
Exercise
What does for (const k in ["x", "y"]) console.log(k + 1); print?
Show answer
It prints "01" and "11". for...in gives the keys as strings, so + 1 joins strings together instead of adding numbers.