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:
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...ofgoes through the values of an array (or string). Use it for lists.for...ingoes 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:
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:
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