Looping Over Objects

Grade 8, page 8 of 13. A one-minute read.

What if you want to go through every property of an object? Here are your options.

for...in

The for...in loop visits every key in an object:

JavaScript
const scores = { math: 90, english: 78, science: 85 };

for (const subject in scores) {
  console.log(`${subject}: ${scores[subject]}`);
}

It prints

math: 90
english: 78
science: 85

Notice that we have to use bracket notation scores[subject] here, because subject is a variable holding the key name.

Tipfor...in vs for...of

They look almost identical, which is a bit mean. Here's how to remember:

  • for...of goes through the values of an array (or string). Use it for lists.
  • for...in goes through the keys in an object. Use it for objects.

Object.keys, Object.values and Object.entries

JavaScript also has three handy functions that turn an object into an array, which you can then loop over or use with any array method:

JavaScript
const scores = { math: 90, english: 78, science: 85 };

console.log(Object.keys(scores));
console.log(Object.values(scores));
console.log(Object.entries(scores));
console.log(`Number of subjects: ${Object.keys(scores).length}`);

It prints

[ 'math', 'english', 'science' ]
[ 90, 78, 85 ]
[ [ 'math', 90 ], [ 'english', 78 ], [ 'science', 85 ] ]
Number of subjects: 3
  • Object.keys(obj) gives an array of all the keys.
  • Object.values(obj) gives an array of all the values.
  • Object.entries(obj) gives an array of [key, value] pairs.

So adding up all the scores is easy:

JavaScript
const scores = { math: 90, english: 78, science: 85 };
let total = 0;

for (const score of Object.values(scores)) {
  total += score;
}

console.log(`Total: ${total}`);

It prints

Total: 253

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning