Frontend is a free bonus on CodeMentor AI β the main product is Python. Register to save your progress and unlock all 290 Frontend lessons + 1,000+ Python lessons.Sign up β free
TaskGiven const fruits = ['apple', 'banana', 'cherry']: use for-of to log each fruit on its own line; then use forEach to log 'index: fruit' (e.g. '0: apple') for each.
Loops: for-of, forEach, and when to use which
75 XP7 minFREE
Theory
Three modern ways to iterate
const items = ["a", "b", "c"];
// for-of: cleanest when you want each value
for (const item of items) {
console.log(item);
}
// .forEach: same idea, method-call style
items.forEach((item, index) => {
console.log(index, item);
});
// classic for: only when you need an index AND control over flow
for (let i = 0; i < items.length; i += 1) {
console.log(i, items[i]);
}When each one fits
| Need | Use |
| Each value, no index | for-of |
| Each value + index | .forEach |
| Step by 2, or break, or index math | classic for |
| Build a new array | .map (covered in C1-04) |
| Reduce to a single value | .reduce |
The break gotcha
items.forEach((item) => {
if (item === "b") return; // 'return' skips THIS iteration, not the loop
});
for (const item of items) {
if (item === "b") break; // actually exits the loop
}forEach has no break. If you need to stop mid-iteration, use for-of (or some / find for searches). The first time you reach for break inside a forEach, you've outgrown it.
Don't reach for vanilla for unless you must
In code review, a plain for (let i = ...) is now a yellow flag β there's almost always a more expressive choice. Keep it for cases where the index does the heavy lifting (matrix walks, sliding windows, step != 1).
Live preview
console output appears hereβ¦