CodingNic

Arrays, Objects & Iteration

Iterating Over Arrays and Objects

Arrays, Objects & Iteration 15 min read

Iterating Over Arrays and Objects

Objectives

By the end of this chapter, you should be able to:

  • Loop over the items in an array with for...of
  • Loop over the keys of an object with for...in
  • Explain when to reach for for...of versus for...in
  • Use .forEach() as another way to loop over an array

💡 Why this matters: You now know several ways to build and reshape arrays and objects. This lesson covers the loops built specifically for stepping through them, so you can process every item or every key without reaching for index math.

for...of: Looping Over Arrays

for...of loops over the values in an array, one at a time.

javascript
const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log(fruit);
}
// apple
// banana
// cherry

Each time through the loop, fruit holds the next value in the array. No index variable, no manual counting, just the values themselves in order. for...of also works on strings and a few other collection types, but arrays are where you’ll use it most.

for...in: Looping Over Object Keys

for...in loops over the keys of an object.

javascript
const scores = { Erin: 90, Sam: 78, Maya: 85 };

for (const player in scores) {
  console.log(player);
}
// Erin
// Sam
// Maya

player holds each key as a string, not the value. To get the value, use the key with bracket notation.

javascript
const scores = { Erin: 90, Sam: 78, Maya: 85 };

for (const player in scores) {
  console.log(player, scores[player]);
}
// Erin 90
// Sam 78
// Maya 85

for...of vs for...in: Which One When

This mix-up trips up a lot of beginners, so here’s the one-sentence rule: use for...of to loop over the values in an array, and for...in to loop over the keys of an object.

Technically, for...in can run on an array too, but it hands you the indexes as strings ("0", "1", "2") instead of the values, which is rarely what you want.

javascript
const fruits = ["apple", "banana"];

for (const index in fruits) {
  console.log(index);
}
// 0
// 1

Stick to for...of for arrays and for...in for objects, and you’ll avoid this mistake entirely.

Revisiting .forEach()

.forEach() is another way to loop over an array. Like .map(), .filter(), and .reduce() from earlier in this module, it’s a higher-order function: it takes a callback and calls it once per item.

javascript
const fruits = ["apple", "banana", "cherry"];

fruits.forEach((fruit) => {
  console.log(fruit);
});
// apple
// banana
// cherry

The key difference from .map(): .forEach() doesn’t return a new array. It always returns undefined. Use .forEach() when you just want to do something with each item, like logging it, and use .map() when you want a new, transformed array back.

javascript
const nums = [1, 2, 3];
const result = nums.forEach((n) => n * 2);
console.log(result);
// undefined

Between for...of and .forEach() for arrays, either works. for...of supports break and continue to stop or skip early; .forEach() does not. Reach for for...of when you might need to exit the loop early, and .forEach() when you’re always processing every item.

Try It

  1. Given const cities = ["Nairobi", "Lagos", "Accra"], log each one using for...of.
  2. Given const inventory = { apples: 12, bananas: 5, cherries: 30 }, log each key and its value using for...in.
  3. Run for...in directly on const cities = ["Nairobi", "Lagos", "Accra"] and observe that you get indexes, not values. Explain in a comment why for...of would have been the better choice.
  4. Rewrite exercise 1 using .forEach() instead of for...of.

Recap

  • for...of loops over the values in an array (or other iterable).
  • for...in loops over the keys of an object; use objectName[key] to get each value.
  • Use for...of for arrays and for...in for objects. Running for...in on an array gives you string indexes, not values.
  • .forEach() is another way to loop over an array. Unlike .map(), it always returns undefined, it’s for doing something with each item, not building a new array.

Next lesson: exercises pulling together everything from this module.