Skip to main content
eLearner.app
Module 5 · Lesson 2 of 418/32 in the course~10 min
Module lessons (2/4)

for…of and for…in

JavaScript has two "ergonomic" loops that should not be confused:

  • for…of iterates the values of an iterable collection (array, string, Set, Map...).
  • for…in iterates the enumerable keys of an object.

They are close cousins and easily swapped — using the wrong one is one of the language's first traps.

for…of for arrays and strings

JS
const colori = ['rosso', 'verde', 'blu'];
for (const c of colori) {
  console.log(c); // 'rosso', 'verde', 'blu'
}

for (const ch of 'abc') {
  console.log(ch); // 'a', 'b', 'c'
}

It does not give you the index. If you also need the index, use entries():

JS
for (const [i, c] of colori.entries()) {
  console.log(i, c); // 0 rosso, 1 verde, 2 blu
}

for…in for objects

JS
const utente = { nome: 'Anna', eta: 30, citta: 'Roma' };
for (const chiave in utente) {
  console.log(chiave, utente[chiave]); // 'nome' 'Anna', ...
}

When NOT to confuse them

JS
const colori = ['rosso', 'verde', 'blu'];

// SBAGLIATO: stampa gli indici come stringhe!
for (const x in colori) {
  console.log(x); // '0', '1', '2'
}

// GIUSTO
for (const x of colori) {
  console.log(x); // 'rosso', 'verde', 'blu'
}

Try it

Exercise#js.m5.l2.e1
Attempts: 0Loading…

Define `concat(words)` that, given a list of strings, returns a string with all of them concatenated, separated by a space. Use for…of.

Loading editor…
Show hint

Accumulate into a string; add the space only if it is not the first word.

Solution available after 3 attempts

Review exercise

Exercise#js.m5.l2.e2
Attempts: 0Loading…

Define `positiveValues(obj)` that returns an array with the object's values that are numbers > 0. Use for…in. The order must match the iteration order of the keys.

Loading editor…
Show hint

Loop with for...in over the keys, filter with typeof and > 0, push into the results.

Solution available after 3 attempts