Прескочи на главни садржај
Frontend je besplatan bonus na CodeMentor AI — glavni proizvod je Python. Registruj se da sačuvaš napredak i otključaš svih 299 Frontend lekcija + 1,100+ Python lekcija.Региструј се — бесплатно
← ⚡ JavaScript & the browser·Модул C1 · Лекција 9
ЗадатакGiven 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.

Петље: фор-оф, форЕацх и када користити које

75 XP7 minFREE
Теорија

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 картице
Живи преглед
console output appears here…
← ПретходнаСледећа лекција →

Један савет за Python или веб дневно — на имејл

Кратко, ручно писано, без спама. Одјава у једном клику.