for...of, for...in and week 3 practice
Walking through the elements of a collection is so frequent that JavaScript has loops designed for it. The for...of loop goes through the values of any iterable object: arrays, strings, Map and Set. It is shorter and safer than a classic for because you do not need to manage an index or worry about limits. Although we will study arrays in depth in week 4, here we already use them in a simple way.
const fruits = ['apple', 'pear', 'grape'];
for (const fruit of fruits) {
console.log(fruit);
}
for (const letter of 'JS!') {
console.log(letter); // J, S, !
}
// When you also need the index, use entries()
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit); // 0 apple, 1 pear, 2 grape
}Notice that we use const inside the parentheses: on each turn a new variable is created, so there is no problem. If you need the index, entries() gives pairs of index and value, which we unpack here with brackets (we will study this in week 4).
for...in walks keys
The for...in loop goes through the keys (property names) of an object. It is useful with simple objects, but you should not use it with arrays: it walks indexes as text and may include inherited properties. An easy rule to remember: for...of for values of collections, for...in for keys of objects. For objects there is also Object.entries, which we will see in week 6.
const person = { name: 'Eva', age: 28, city: 'Lima' };
for (const key in person) {
console.log(key, '->', person[key]);
}
// name -> Eva
// age -> 28
// city -> Lima
// Practical case: find the largest number
const numbers = [4, 19, 7, 31, 12];
let max = numbers[0];
for (const n of numbers) {
if (n > max) max = n;
}
console.log(max); // 31Choosing the right loop
- classic for: when you know the number of turns or need to control the counter.
- while: when you repeat until a condition changes and you do not know how many turns there will be.
- for...of: when you want each value of an array, string or other iterable.
- for...in: when you want the keys of an object.
- Later: array methods such as forEach, map and filter, which are even more expressive.
A pattern you will see again and again is the accumulator: a variable that starts with an initial value (0, empty text, empty list) and is updated on every turn. With it you add totals, count matches or build results. Combine it with an if inside the loop and you can already solve many real problems, such as counting vowels or computing an average.
const sentence = 'Learning JavaScript is fun';
let vowels = 0;
for (const char of sentence.toLowerCase()) {
if ('aeiou'.includes(char)) vowels++;
}
console.log(vowels); // 8How to attack a new problem
When you face an exercise, do not start by writing code. First describe the problem in your own words, then think of a small example and solve it by hand, noting each step. Those steps are your algorithm. Only then do you translate them into JavaScript, one instruction at a time, testing with console.log. If something fails, reduce the problem: try with a list of two elements instead of a hundred. This way of working, dividing and testing, will serve you throughout your career and avoids the paralysis of staring at a blank screen.
Testez vos acquis
Question 1 sur 6Which loop walks the values of an array?
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères