Skip to the content

Lesson 42 of 296

Looping over arrays and objects

What you will learn

  • Four ways to loop over an array
  • for...of vs for...in
  • Looping over an object's keys, values and both
  • Which loop to choose
On this page

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 30

for...of vs for...in

This is a classic interview question.

for...offor...in
Gives youValuesKeys (property names)
Use withArrays, strings, Maps, SetsPlain objects
On an arrayValues: "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 iterable

Only 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);       4995

Example: 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?

GoalUse
Do something with each value of an arrayfor...of
Need the index, or loop backwardsClassic for
Need to stop earlyfor...of or for with break
Build a new array from an old onemap / filter
Loop over an objectObject.entries() with for...of
Unknown number of repeatswhile

Common mistakes

  • for...in on arrays.
  • for...of on plain objects.
  • Trying to break out of forEach.
  • 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

WordMeaning
IterateGo through items one at a time
IterableSomething for...of can loop over: arrays, strings, Maps, Sets
for...ofLoops over values
for...inLoops over keys of an object
forEachAn array method that calls a function for each item
DestructuringTaking 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.