Naar hoofdinhoud
← ⚑ JavaScript & the browserΒ·Module C6 Β· Les 1
OpdrachtGiven 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
Theorie

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.

πŸ”’

Registreer om te beginnen met coderen

Theorie is voor iedereen. De editor, live preview en check ontgrendelen met een 7-daagse gratis proefperiode β€” kaart vereist, opzegbaar.

Registreren β€” gratis proef β†’

De eerste 10 lessen in elke track zijn gratis. Geen kaart nodig.

← VorigeVolgende les β†’

EΓ©n Python- of web-tip per dag β€” per e-mail

Kort, met de hand geschreven, geen spam. Met één klik afmelden.