• Fri, May 2026

Suggested:

Looping Through an Object in JavaSript

Looping Through an Object in JavaSript

Looping Through an Object in JavaSript

What is an Object?

 
 
let student = {
  name: "Ada",
  age: 16,
  class: "SS2"
};
 

👉 Key-value pair:

  • name → "Ada"
  • age → 16

🔹 Looping Through an Object

✅ Method 1: for...in (MAIN WAY)

 
 
let student = {
  name: "Ada",
  age: 16,
  class: "SS2"
};

for (let key in student) {
  console.log(key, student[key]);
}
 

🔥 Output

 
name Ada
age 16
class SS2
 

🔍 Breakdown

  • key → property name (name, age)
  • student[key] → value

👉 IMPORTANT:

 
 
student[key] // ✅ correct
student.key  // ❌ wrong (will not work here)
 

🔹 Format it better

 
 
for (let key in student) {
  console.log(key + ": " + student[key]);
}
 

🔹 Real Use Case (VERY IMPORTANT FOR YOU)

Loop through multiple students (array of objects)

 
 
let students = [
  { name: "Ada", age: 16 },
  { name: "Chidi", age: 17 },
  { name: "Emeka", age: 18 }
];

for (let student of students) {
  console.log(student.name, student.age);
}
 

🔥 Output

 
Ada 16
Chidi 17
Emeka 18
 

🔹 Combine Both (POWERFUL)

 
 
for (let student of students) {
  for (let key in student) {
    console.log(key + ": " + student[key]);
  }
  console.log("----");
}
 

🔥 Output

 
name: Ada
age: 16
----
name: Chidi
age: 17
----
name: Emeka
age: 18
----
 

🔹 Modern Method (Object.keys)

 
 
let student = {
  name: "Ada",
  age: 16
};

Object.keys(student).forEach(key => {
  console.log(key, student[key]);
});
 

🔹 Even Better (Object.entries 🔥)

 
 
Object.entries(student).forEach(([key, value]) => {
  console.log(key, value);
});
 

⚠️ Common Mistakes

❌ Using for...of on object directly

 
 
for (let item of student) {
 

👉 ❌ ERROR — objects are not iterable


💪 Practice (DO THIS)

1.

 
 
let car = {
  brand: "Toyota",
  model: "Camry",
  year: 2020
};
 

👉 Print:

 
brand: Toyota
model: Camry
year: 2020
 

2.

Loop through:

 
 
let users = [
  { name: "John", role: "Admin" },
  { name: "Mary", role: "User" }
];
 

👉 Print:

 
John - Admin
Mary - User
 

🚀 For YOU (VERY IMPORTANT)

This is EXACTLY what you’ll use in:

  • API responses (Laravel → JSON)
  • Student data tables
  • Dashboard rendering
  • Admin panels
Your experience on this site will be improved by allowing cookies Cookie Policy