Module lessons (2/4)
for…of and for…in
JavaScript has two "ergonomic" loops that should not be confused:
for…ofiterates the values of an iterable collection (array, string, Set, Map...).for…initerates 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
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():
for (const [i, c] of colori.entries()) {
console.log(i, c); // 0 rosso, 1 verde, 2 blu
}for…in for objects
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
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
Define `concat(words)` that, given a list of strings, returns a string with all of them concatenated, separated by a space. Use for…of.
Show hint
Accumulate into a string; add the space only if it is not the first word.
Solution available after 3 attempts
Review exercise
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.
Show hint
Loop with for...in over the keys, filter with typeof and > 0, push into the results.
Solution available after 3 attempts