Към основното съдържание
Frontend е безплатен бонус в CodeMentor AI — основният продукт е Python. Регистрирай се, за да запазиш напредъка си и да отключиш всички 299 Frontend урока + 1,100+ Python урока.Регистрирай се — безплатно
← ⚡ 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.

Цикли: for-of, forEach и кога да използвате кое

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 или уеб на ден — на имейл

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