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

Iterating over collections

Manipulating collections almost always means iterating: walking through the elements one at a time and doing something for each. In this lesson we look at the basic syntaxes; in the functional arrays module (map / filter / reduce) we'll learn to write them more declaratively.

for…of for arrays

It's the loop you'll want to use almost always to iterate an array: it extracts the value at every step.

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

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

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 — with caution

for…in iterates the keys (strings) of an object:

JS
const utente = { nome: 'Anna', eta: 28 };
for (const k in utente) {
  console.log(`${k} = ${utente[k]}`);
}

Object.keys / values / entries

These are the robust way to iterate an object. They return arrays, and so they combine very well with for…of:

JS
const utente = { nome: 'Anna', eta: 28 };

Object.keys(utente); // ['nome', 'eta']
Object.values(utente); // ['Anna', 28]
Object.entries(utente); // [['nome', 'Anna'], ['eta', 28]]

for (const [k, v] of Object.entries(utente)) {
  console.log(`${k} → ${v}`);
}

Classic for

The "old-school" for still exists. You'll use it rarely, but it's useful when you need fine control over the index (skipping elements, iterating backwards):

JS
for (let i = 0; i < colori.length; i++) {
  console.log(i, colori[i]);
}

// Backwards
for (let i = colori.length - 1; i >= 0; i--) {
  console.log(colori[i]);
}

Try it

Exercise#js.m3.l4.e1
Attempts: 0Loading…

Given `numbers = [3, 5, 7]`, compute the sum of all elements (15) by iterating with for...of. The last expression must evaluate to the sum.

Loading editor…
Show hint

for (const n of numbers) { sum = sum + n; }

Solution available after 3 attempts

Review exercise

Exercise#js.m3.l4.e2
Attempts: 0Loading…

Given `prices = { mela: 0.4, pera: 0.55, banana: 0.3 }`, return the TOTAL NUMBER of entries in the object (3) using Object.keys.

Loading editor…
Show hint

Object.keys(obj) returns an array; .length tells how many keys there are.

Solution available after 3 attempts