JavaScript for…in Loop
Learn how to loop through object properties efficiently using the JavaScript for…in statement.
In JavaScript, the for…in loop is used to iterate over the enumerable property names (keys) of an object. It executes a block of code once for each property found in the object.
This loop is commonly used when working with plain JavaScript objects, such as configuration objects, user data, or dynamically generated key-value pairs.
The for…in loop iterates only over properties whose enumerable attribute is set to true. It also includes inherited enumerable properties unless explicitly filtered.
Syntax of JavaScript for…in Loop
for (const key in object) {
// code to execute
}
- key – A variable that stores each property name of the object.
- object – The object whose enumerable properties are iterated.
Example: Iterating Over Object Properties Safely
JavaScript Example
const product = {
name: "Laptop",
price: 1200,
brand: "TechPro",
inStock: true
};
for (const key in product) {
if (product.hasOwnProperty(key)) {
console.log(`${key}: ${product[key]}`);
}
}
Try it Yourself »
Important Notes & Best Practices
-
Avoid using for…in to iterate over arrays.
Use
for,forEach(), orfor…ofinstead. -
Always use
hasOwnProperty()to prevent iterating over inherited properties. - The order of properties is not guaranteed, so do not rely on it for sorting.
How Does the JavaScript for…in Loop Work?
The JavaScript for…in loop iterates over the enumerable property names (keys) of an object. During each iteration, the current property name is assigned to a variable, allowing you to access the corresponding value inside the loop body.
This loop is especially useful when working with objects that store related data in key–value pairs, such as user profiles, configuration settings, or API responses.
The execution flow of the for…in loop works as follows:
- In the first iteration, the loop assigns the first property name of the object to the loop variable and executes the code block.
- In each subsequent iteration, the next property name is assigned, and the loop body runs again.
- The loop continues until all enumerable properties of the object have been processed.
Example 1: Reading Values from an Object
JavaScript Example
const browserUsage = {
Chrome: 65,
Safari: 18,
Firefox: 10,
Edge: 7
};
for (const browser in browserUsage) {
console.log(browserUsage[browser]);
}
Try it Yourself »
Example 2: Accessing Both Keys and Values
JavaScript Example
const employeeSalaries = {
Alice: 52000,
Michael: 68000,
Sophia: 61000
};
for (const employee in employeeSalaries) {
const salary = "$" + employeeSalaries[employee];
console.log(`${employee}: ${salary}`);
}
Try it Yourself »
Explanation:
Here, the for…in loop iterates over each property of the
employeeSalaries object. The property name represents the
employee, and its value represents the salary. The value is formatted
by prefixing it with a dollar sign before being displayed.
Using a for Loop Inside a for…in Loop
In this pattern, a traditional for loop is nested inside a for…in loop. The outer for…in loop iterates through the enumerable properties of an object, while the inner for loop performs repeated operations for each property.
This approach is useful when each object property requires multiple calculations, iterations, or validations—such as generating reports, applying formulas, or processing grouped data.
Syntax
for (const key in object) {
for (let i = 0; i < limit; i++) {
// code to execute
}
}
Example: Nested for Loop with Object Data
JavaScript Example
const monthlySales = {
January: 1200,
February: 1500,
March: 1800
};
for (const month in monthlySales) {
console.log(`Month: ${month}`);
for (let quarter = 1; quarter <= 3; quarter++) {
console.log(
` Projection ${quarter}: $${monthlySales[month] * quarter}`
);
}
}
Try it Yourself »
Explanation:
The outer for…in loop iterates through each month in the
monthlySales object. For every month, the inner
for loop runs three times to generate projected sales
values. This demonstrates how nested loops can be used to perform
multiple calculations for each object property.
Important Facts About the JavaScript for…in Loop
-
The for…in loop is not recommended for iterating over arrays,
especially when the order of elements matters. Use
for,forEach(), orfor…ofinstead. - The iteration order of a for…in loop is not strictly guaranteed and should not be relied upon for ordered data structures.
- When used with objects, the order in which properties are visited may differ from the order in which they were originally defined.
- The for…in loop iterates over all enumerable properties, including those inherited through the prototype chain, unless filtered explicitly.
Key Features of the JavaScript for…in Loop
Designed for Object Traversal
The for…in loop is primarily designed to iterate over the enumerable properties of JavaScript objects. It accesses both an object’s own properties and those inherited via the prototype chain.
Easy Access to Property Keys
Each iteration returns a property key as a string, enabling developers to dynamically access, update, or evaluate object values using bracket notation.
Unpredictable Enumeration Order
Although modern JavaScript engines follow a more consistent pattern, the for…in loop does not guarantee a reliable enumeration order across environments. It should therefore be avoided when predictable ordering is required.
Flexible but Purpose-Specific
The for…in loop can iterate over properties of custom objects as well as built-in types such as Object, Array, and String. However, it is most effective and reliable when used for plain object traversal.
Frequently Asked Questions (FAQ)
What is a for…in loop in JavaScript?
The for…in loop in JavaScript is a control structure used to iterate over the enumerable property names (keys) of an object. It allows developers to examine or manipulate each property dynamically.
const user = { name: 'John', age: 25 };
for (const key in user) {
console.log(key);
}
What does the for…in loop iterate over?
The for…in loop iterates over all
enumerable properties of an object. This includes
both the object’s own properties and those inherited through the
prototype chain, unless filtered using
hasOwnProperty().
Why should the for…in loop not be used for arrays?
The for…in loop is not suitable for arrays because it
iterates over property names rather than numeric indexes and does not
guarantee the order of elements. For array iteration, prefer
for, forEach(), or for…of.
What is the difference between for…in and for…of?
The for…in loop iterates over the keys of an object, while the for…of loop iterates over the values of iterable objects such as arrays, strings, maps, and sets.
for (const key in obj) {
console.log(key); // property names
}
for (const value of arr) {
console.log(value); // element values
}
How can I prevent inherited properties in a for…in loop?
To exclude inherited properties, use the
hasOwnProperty() method inside the loop. This ensures
that only the object’s own properties are processed.
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key);
}
}