Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C6 · Lekcja 1
ZadanieGiven const arr = [1,2,3] and const obj = {a: 1, b: 2, c: 3}: use for-of to log each value of arr; use Object.entries + for-of to log "<key>=<value>" for each obj entry.

for-of vs forEach vs for-in

100 XP7 min
Teoria

Three loops, three jobs

for-of walks the values of any iterable. Works on Array, Map, Set, string, NodeList, generators — anything implementing the iteration protocol.

for (const x of [10, 20, 30]) console.log(x); // 10, 20, 30
for (const ch of "hi")        console.log(ch); // "h", "i"

forEach is a method on Array (and Map, Set) with a callback. It's older and less flexible — you can't break, continue, or await inside it without ceremony.

[10, 20, 30].forEach((x) => console.log(x));

for-in walks the enumerable property keys of an object. Use it on plain objects, NOT arrays — it also picks up inherited properties.

const obj = { a: 1, b: 2 };
for (const key in obj) console.log(key); // "a", "b"

The rule

  • Need values from a collection → for-of.
  • Need to await/break/early-exit → for-of.
  • Need object keys → Object.keys(obj) + for-of, or for-in if you trust the source.
  • Need a one-liner side effect on an array → forEach.

for-of is the default. forEach is rarely the right pick once you know for-of.

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.