0
0
Javascriptprogramming~5 mins

Iterating over objects in Javascript

Choose your learning style9 modes available
Introduction
Iterating over objects helps you look at each piece of information stored inside, one by one.
When you want to print all details of a user stored in an object.
When you need to check or change every setting in a configuration object.
When you want to count how many properties an object has.
When you want to collect all keys or values from an object for further use.
Syntax
Javascript
for (const key in object) {
  // use object[key] here
}
The 'for...in' loop goes through all keys in the object.
Use object[key] to get the value for each key.
Examples
This prints each key and its value from the person object.
Javascript
const person = {name: 'Anna', age: 25};
for (const key in person) {
  console.log(key + ': ' + person[key]);
}
This checks each setting and prints if it is enabled (true).
Javascript
const settings = {darkMode: true, fontSize: 14};
for (const key in settings) {
  if (settings[key]) {
    console.log(key + ' is enabled');
  }
}
Using Object.keys() to get keys, then looping with for...of.
Javascript
const scores = {alice: 10, bob: 15};
const keys = Object.keys(scores);
for (const key of keys) {
  console.log(key + ' scored ' + scores[key]);
}
Sample Program
This program prints each property and its value from the car object.
Javascript
const car = {
  make: 'Toyota',
  model: 'Corolla',
  year: 2020
};

for (const key in car) {
  console.log(`${key}: ${car[key]}`);
}
OutputSuccess
Important Notes
The 'for...in' loop also goes through inherited properties, so use hasOwnProperty() if you want only own properties.
You can also use Object.keys(), Object.values(), or Object.entries() to get arrays for looping.
Remember that the order of keys in objects is not guaranteed, so don't rely on it.
Summary
Use 'for...in' to loop over all keys in an object.
Access values with object[key] inside the loop.
For safer loops, consider Object.keys() with 'for...of'.