For Loops
Loops allow you to run the same block of code multiple times with varying values.
Loops allow you to run the same block of code multiple times with varying values.
const items = ["alpha", "beta", "gamma"];
// for...of (Values in Iterables: Arrays, Sets, Maps)
for (const [index, val] of items.entries()) {
console.log(`${index}: ${val}`);
}
// for...in (Keys in Objects ONLY)
const config = { host: "localhost", port: 8080 };
for (const key in config) {
if (Object.hasOwn(config, key)) {
console.log(`${key} = ${config[key]}`);
}
}
for...in iterates over all enumerable property keys, including prototype methods and string indices in arbitrary order. Always use for...of or array methods for arrays.forEach does NOT await promises! Passing an async callback runs promises concurrently and exits immediately before completion. Use for (const x of items) await ....for (var i = 0; ...) shares a single variable across all loop iterations, so asynchronous callbacks (like setTimeout) all log the final value. Use let to create per-iteration bindings.splice() or push() inside an index-based for loop alters the array length and shifts elements, causing items to be skipped.i-- instead of i++ locks the main browser thread in an infinite loop, crashing the tab.