How to use For…in the loop In Javascript

The for…in loop iterates over the enumerable properties of an object, including those inherited from its prototype chain. It’s commonly used for iterating over object properties and performing operations based on each property’s value or key.

Example: Iterating through a JavaScript object with arrays and nested objects using built-in methods.

Javascript




let course = {
  title: "Java",
  price: 30000,
  Instructors: ["Kamal Sir", "Anuv Sir"],
  Materials: {
    book1: "Effective Java",
    book2: "Head First Java",
  },
};
 
for (let key in course) {
  if (course.hasOwnProperty(key)) {
    console.log(key, course[key]);
  }
}


Output

title Java
price 30000
Instructors [ 'Kamal Sir', 'Anuv Sir' ]
Materials { book1: 'Effective Java', book2: 'Head First Java' }

How to Iterate JavaScript Object Containing Array and Nested Objects ?

JavaScript provides us with several built-in methods through which one can iterate over the array and nested objects using the for…in loop, Object.keys(), Object.entries(), and Object.values(). Each method serves a distinct purpose in iterating over object properties, keys, and values which are explained as follows:

Table of Content

  • Using For…in the loop
  • Using Object.keys() method
  • Using Object.entries() method
  • Using Object.values() method

Similar Reads

Using For…in the loop

The for…in loop iterates over the enumerable properties of an object, including those inherited from its prototype chain. It’s commonly used for iterating over object properties and performing operations based on each property’s value or key....

Using Object.keys() method

...

Using Object.entries() method

The Object.keys() method returns an array of a given object’s enumerable property names. This method provides a way to access the keys of an object, which can be useful for iterating over its properties or performing operations based on its keys. It returns an array containing the strings that represent the names of the object’s enumerable properties....

Using Object.values() method

...

Contact Us