JavaScript for…in Loop: Iterating Over Objects

JavaScript for in loop

You may need to loop through properties when you work with objects in JavaScript. The for...in loop helps you do that.

It gives you each key in the object, one by one. You can then use those keys to get the values.

How for...in Loop Works in JavaScript

The for...in loop helps you go through all the keys in an object. It does not give you the values directly. It gives you the names of the keys. You can then use each key to get its value from the object.

The for...in loop is a built-in JavaScript statement. It goes over all enumerable properties in an object. These are the keys that are not hidden or marked as non-enumerable.

Here is the syntax:

for (let key in object) {
  // your code here
}
  • key is a variable name. It holds the name of each key.
  • object is the object you want to loop through.

The loop starts at the first key in the object. It then moves to the next key, one at a time. You can run code inside the loop block for each key. This lets you read or change values in the object.

The loop does not care about the order of the keys. That means you should not use it if the key order matters.

Here is a simple example:

const user = {
  name: "Lebo",
  age: 30,
  country: "South Africa"
};

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

This loop prints:

name: Lebo  
age: 30
country: South Africa

In this case:

  • The loop gets each key: name, age, and country.
  • It then uses the key to get the value: user[key].

This is useful when you do not know all the keys in advance or when you want to process them all the same way.

Access the Object Properties Using the for...in Loop

The for...in loop gives you access to each key in an object. You can use it to get the value once you have the key. JavaScript lets you do this with bracket notation.

Here is what that looks like:

const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2020
};

for (let key in car) {
  console.log("Key:", key);
  console.log("Value:", car[key]);
}

The output:

Key: brand
Value: Toyota
Key: model
Value: Corolla
Key: year
Value: 2020

This loop prints each key and its matching value. You must use square brackets [] with the key. Dot notation will not work here because key is a variable.

You can also use this pattern to update values:

const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2020
};

for (let key in car) {
  if (typeof car[key] === "number") {
    car[key] += 1;
  }
}

console.log(car);

Output:

{ brand: 'Toyota', model: 'Corolla', year: 2021 }

This adds 1 to all number values in the object.

Enumerate Over Arrays with the for...in Loop

You can use the for...in loop with arrays, but it is not a good choice. The loop gives you the index keys, not the values. It also includes extra properties if someone added custom ones to the array.

Here is an example:

const fruits = ["apple", "banana", "cherry"];

for (let index in fruits) {
  console.log(index, fruits[index]);
}

This prints:

0 apple  
1 banana
2 cherry

The loop goes over the indexes: 0, 1, 2. Then it uses each index to get the fruit.

The problem shows up when the array has extra properties:

fruits.color = "red";

for (let index in fruits) {
  console.log(index, fruits[index]);
}

Output:

0 apple
1 banana
2 cherry
color red

Now the loop also prints:

color red

That is not part of the data you expected. This is why for...in is not safe for arrays. You should use for, for...of, or forEach when you work with array items.

Filter Own Properties with hasOwnProperty()

The for...in loop does not stop at the object’s own properties. It also includes keys from the object’s prototype chain. This can lead to unexpected results if you do not check which keys belong to the object itself.

Use the hasOwnProperty() method inside the loop to avoid this. This method checks if the object has the key directly, not through inheritance.

Here is an example:

const person = {
  name: "Zanele",
  age: 25
};

Object.prototype.extra = "should not show up";

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

Output:

name: Zanele
age: 25

The loop would include extra without the hasOwnProperty() check. It only prints the real properties: name and age with the check.

This check is important when you loop through objects that come from outside your code, like data from APIs or libraries.

Compare for...in with Other Loop Types

It loops through object keys. But JavaScript gives you other loop types that work better in different cases. Each one has a clear use.

for...in vs for...of:

  • for...in gives you keys (property names)
  • for...of gives you values (for arrays, strings, maps, etc.)
const colors = ["red", "green", "blue"];

for (let index in colors) {
  console.log(index); // 0, 1, 2
}

for (let color of colors) {
  console.log(color); // red, green, blue
}

Output:

0
1
2
red
green
blue

Use for...in for objects. Use for...of for arrays or other iterable data.

for...in vs Object.keys() + for:

You can use Object.keys() to get an array of an object’s own keys. Then use a regular for loop to go through them. This avoids inherited properties.

const user = { name: "Lebo", role: "admin" };

const keys = Object.keys(user);
for (let i = 0; i < keys.length; i++) {
  let key = keys[i];
  console.log(key + ": " + user[key]);
}

Output:

name: Lebo
role: admin

This works like for...in with a hasOwnProperty() check.

for...in vs forEach():

The forEach() is for arrays. It loops through values, not keys. It is shorter to write but does not work on plain objects.

const nums = [10, 20, 30];

nums.forEach(function (value, index) {
  console.log(index, value);
});

Output:

0 10
1 20
2 30

Use forEach() when you work with arrays and do not need to break out early.

Iterate Over Nested Objects

Some objects contain other objects inside them. These are called nested objects. You can use a for...in loop inside another for...in loop to work with them.

Here is an example:

const student = {
  name: "Thabo",
  grades: {
    math: 80,
    science: 85,
    history: 78
  }
};

for (let key in student) {
  if (student.hasOwnProperty(key)) {
    if (typeof student[key] === "object") {
      for (let innerKey in student[key]) {
        if (student[key].hasOwnProperty(innerKey)) {
          console.log(innerKey + ": " + student[key][innerKey]);
        }
      }
    } else {
      console.log(key + ": " + student[key]);
    }
  }
}

Output:

name: Thabo
math: 80
science: 85
history: 78

This loop handles both top-level keys and nested keys. It checks each value. It starts a second loop to go through that inner object if the value is an object.

You can use this pattern when the shape of the object is known. If the nesting gets deeper, you may want to use a function to handle it.

JavaScript for...in Examples

Example 1 – Loop through nested objects:

const user = {
  name: "Alice",
  contact: {
    email: "[email protected]",
    phone: "123-456-7890"
  }
};

for (const key in user) {
  if (typeof user[key] === "object") {
    for (const innerKey in user[key]) {
      console.log(`${innerKey}: ${user[key][innerKey]}`);
    }
  } else {
    console.log(`${key}: ${user[key]}`);
  }
}

Output:

name: Alice
email: [email protected]
phone: 123-456-7890

This loop checks if a property is an object. It uses a second for...in loop to go through the nested object. This helps you get all values even if they are inside another object.

Example 2 – Skip inherited properties with hasOwnProperty:

const base = { shared: true };
const obj = Object.create(base);
obj.name = "Widget";
obj.price = 25;

for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(`${key}: ${obj[key]}`);
  }
}

Output:

name: Widget
price: 25

This object inherits from base, but we only want to loop through obj‘s own properties. hasOwnProperty() filters out the inherited ones.

Example 3 – Count property types in an object:

const data = {
  id: 123,
  active: true,
  tags: ["js", "loop"],
  details: { created: "2023-01-01" }
};

const typeCount = {};

for (const key in data) {
  const type = typeof data[key];
  typeCount[type] = (typeCount[type] || 0) + 1;
}

console.log(typeCount);

Output:

{ number: 1, boolean: 1, object: 2 }

This loop checks the type of each value and counts how many values share that type. It uses an object to store the counts.

Example 4 – Modify values inside an object:

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

for (const subject in scores) {
  scores[subject] += 5;
}

console.log(scores);

Output:

{ math: 85, science: 95, english: 90 }

This loop goes through each property and adds 5 to the value. It updates the values directly in the original object.

Example 5 – Filter and transform object properties:

const inventory = {
  apple: { price: 1.2, stock: 30 },
  banana: { price: 0.8, stock: 50 },
  cherry: { price: 2.5, stock: 20 },
  date: { price: 3.0, stock: 15 }
};

const lowStock = [];

for (const fruit in inventory) {
  if (inventory[fruit].stock < 25) {
    lowStock.push(fruit);
  }
}

console.log("Fruits with low stock:", lowStock);

Output:

Fruits with low stock: [ 'cherry', 'date' ]

This example filters the inventory object to find fruits with less than 25 items in stock. The for...in loop iterates over each fruit and checks the stock level. It adds the fruit to the lowStock array if the stock is below 25.

Wrapping Up

You learned how the for...in loop works in JavaScript and how to use it to go through object properties. You also saw what to watch out for, especially with arrays and inherited keys.

Here is a quick recap:

  • The for...in loop gives you each key in an object, one at a time.
  • You can use the key with square brackets to get or update the value.
  • This loop works best with plain objects, not arrays.
  • It also includes keys from the prototype chain, so use hasOwnProperty() to filter them.
  • You can loop through nested objects within a for...in loop inside another.
  • Other loop types like for...of, forEach(), and Object.keys() work better for arrays or when you want more control.

Thank you for reading. Here are JavaScript tutorials.

FAQ’s

What is a for...in loop in JavaScript?

The for...in loop in JavaScript is a built-in statement used to iterate over the keys (properties) of an object. It does not give you the values directly but provides each key one by one. You can then use those keys to get the corresponding values from the object. For example:
const user = { name: "Lebo", age: 30, country: "South Africa" };
for (let key in user) {
  console.log(key + ": " + user[key]);
}

Can you use the for...in loop with arrays?

Yes, you can use the for...in loop with arrays, but it is not recommended. The for...in loop iterates over the array's indexes, not the values, and it will include any additional properties added to the array.
const fruits = ["apple", "banana", "cherry"];
for (let index in fruits) {
  console.log(index, fruits[index]);
}
It is not safe because it also includes properties added to the array, which can lead to unexpected results. For arrays, it’s better to use for, for...of, or forEach().

How do you skip inherited properties in a for...in loop?

The for...in loop also iterates over properties from an object's prototype chain. To avoid including inherited properties, use the hasOwnProperty() method. This method checks if the property belongs directly to the object.
const person = { name: "Zanele", age: 25 };
Object.prototype.extra = "should not show up";

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key + ": " + person[key]);
  }
}
Without the hasOwnProperty() check, the loop would include the inherited extra property, but with the check, it only processes the properties of the person object itself.

How do you loop through nested objects in JavaScript?

To iterate through nested objects, you can use a for...in loop inside another for...in loop. This lets you access both the top-level properties and the nested properties of an object.
const student = { name: "Thabo", grades: { math: 80, science: 85, history: 78 } };

for (let key in student) {
  if (typeof student[key] === "object") {
    for (let innerKey in student[key]) {
      console.log(innerKey + ": " + student[key][innerKey]);
    }
  } else {
    console.log(key + ": " + student[key]);
  }
}
This will print both the top-level properties (like name) and the properties within the nested grades object.

What is the difference between for...in and for...of in JavaScript?

The for...in loop iterates over the keys (or property names) of an object, while the for...of loop iterates over the values of iterable objects like arrays, strings, maps, and sets.
Previous Article

JavaScript While Loop: How It Works with Examples

Next Article

Understanding JavaScript Arithmetic Operators

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.