Lesson 42 of 296
Looping over arrays and objects
What you will learn
- Four ways to loop over an array
for...ofvsfor...in- Looping over an object's keys, values and both
- Which loop to choose
On this page
- Four ways to loop over an array
- for...in: for object keys
- for...of vs for...in
- for...of does not work on plain objects
- The modern way to loop over an object
- Looping over a string
- Example: count totals
- Example: count how often each word appears
- Which loop should you choose?
- Common mistakes
- How to say it in an interview
- Key words
Four ways to loop over an array
const fruits = ["apple", "banana", "cherry"];1. Classic for loop
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}Use it when you need the index, need to skip or jump, or loop backwards.
2. for...of
for (const fruit of fruits) {
console.log(fruit);
}The simplest way to get each value. break and continue work. Use const because each loop gets a fresh variable.
To get the index too:
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}3. forEach
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});Calls a function once for every item. You cannot stop it with break, and return only skips the current item. It also does not wait for async functions (Part 5).
4. Array methods: map, filter, reduce
When the goal is to build a new array or value, these are clearer:
const upper = fruits.map((f) => f.toUpperCase());
const long = fruits.filter((f) => f.length > 5);Part 5 teaches them in depth.
for...in: for object keys
for...in loops over the keys of an object.
const user = { name: "Sam", age: 30 };
for (const key in user) {
console.log(key, user[key]);
}Shows:
name Sam
age 30for...of vs for...in
This is a classic interview question.
for...of | for...in | |
|---|---|---|
| Gives you | Values | Keys (property names) |
| Use with | Arrays, strings, Maps, Sets | Plain objects |
| On an array | Values: "apple" | Index strings: "0", "1" |
Do not use for...in on arrays. It gives index numbers as strings, and it can also include extra properties added to the array or inherited from elsewhere.
Remember it this way: "in" gives the keys that are in the object; "of" gives the values of a list.
for...of does not work on plain objects
for (const x of user) { } TypeError: user is not iterableOnly things that are iterable (arrays, strings, Maps, Sets) work with for...of. A plain object is not iterable.
The modern way to loop over an object
Turn the object into an array first, then use for...of:
for (const key of Object.keys(user)) {
console.log(key);
}
for (const value of Object.values(user)) {
console.log(value);
}
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}The [key, value] part is called destructuring (Part 5). It takes the two items out of each small [key, value] array.
Looping over a string
for (const char of "hey") {
console.log(char);
}Shows h, e, y.
Example: count totals
const basket = [
{ name: "Kettle", pricePence: 2999, qty: 1 },
{ name: "Mug", pricePence: 499, qty: 4 }
];
let total = 0;
for (const item of basket) {
total += item.pricePence * item.qty;
}
console.log(total); 4995Example: count how often each word appears
const words = ["red", "blue", "red", "green", "red"];
const counts = {};
for (const word of words) {
if (counts[word] === undefined) {
counts[word] = 0;
}
counts[word]++;
}
console.log(counts); { red: 3, blue: 1, green: 1 }This "count with an object" pattern appears in many interview problems (Part 10, hashing).
Which loop should you choose?
| Goal | Use |
|---|---|
| Do something with each value of an array | for...of |
| Need the index, or loop backwards | Classic for |
| Need to stop early | for...of or for with break |
| Build a new array from an old one | map / filter |
| Loop over an object | Object.entries() with for...of |
| Unknown number of repeats | while |
Common mistakes
for...inon arrays.for...ofon plain objects.- Trying to
breakout offorEach. - Changing an array (adding or removing items) while looping over it.
How to say it in an interview
"for...of iterates over the values of iterables like arrays and strings; for...in iterates over the enumerable keys of an object, so I do not use it on arrays. To loop over an object I use Object.entries with for...of and destructuring. forEach cannot be stopped with break, so if I need to exit early I use for...of. And when I am transforming data I prefer map and filter."
Key words
| Word | Meaning |
|---|---|
| Iterate | Go through items one at a time |
| Iterable | Something for...of can loop over: arrays, strings, Maps, Sets |
| for...of | Loops over values |
| for...in | Loops over keys of an object |
| forEach | An array method that calls a function for each item |
| Destructuring | Taking values out of an array or object into variables |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.