Vai al contenuto principale
Il Frontend è un bonus gratuito su CodeMentor AI — il prodotto principale è Python. Registrati per salvare i tuoi progressi e sbloccare tutte le 299 lezioni di Frontend + 1,100+ lezioni di Python.Registrati — gratis
← ⚡ JavaScript & the browser·Modulo C1 · Lezione 9
CompitoGiven 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.

Cicli: for-of, forEach e quando utilizzare quale

75 XP7 minFREE
Teoria

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

NeedUse
Each value, no indexfor-of
Each value + index.forEach
Step by 2, or break, or index mathclassic 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).

2 schede
Anteprima live
console output appears here…
← PrecedenteProssima lezione →

Ricevi un consiglio Python o web al giorno — via email

Breve, scritto a mano, niente spam. Disiscriviti in un clic.