JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Loop For In


The for...in loop in JavaScript is a powerful tool used to iterate over the properties of an object. Unlike the standard for loop, which is generally used for arrays, the for...in loop is specifically designed to traverse all enumerable properties of an object. Understanding this loop is essential for working with objects, managing dynamic data, and performing operations on key-value pairs efficiently.

This tutorial covers the syntax, practical examples, common mistakes, best practices, and real-world applications of the for...in loop in JavaScript.

Why the For In Loop Is Important

The for...in loop is important because it allows you to:

  • Iterate over all enumerable properties of an object.

  • Dynamically access object keys without knowing them in advance.

  • Modify, read, or manipulate property values programmatically.

  • Reduce repetitive code when working with complex objects.

  • Combine with other JavaScript structures for more dynamic logic.

Without for...in, accessing each property of an object would require manual calls, making your code repetitive and less maintainable.

Syntax

The basic syntax of a for...in loop is:

for (let key in object) {
  // Code to execute for each property
}
  • key – Represents the current property name in each iteration.

  • object – The object whose properties are being traversed.

  • The loop iterates over all enumerable properties, including those inherited from the prototype chain, unless filtered.

Example 1: Basic Object Iteration

let person = {
  name: "Emma",
  age: 25,
  profession: "Developer"
};

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

Output:

name: Emma
age: 25
profession: Developer

Here, the loop iterates over each property of the person object and logs both the key and its value.

Iterating Arrays (Not Recommended)

Although possible, using for...in for arrays is not recommended because it iterates over enumerable properties, not just numeric indices. It may include unexpected properties if the array has custom properties.

let colors = ["Red", "Green", "Blue"];
colors.customProperty = "Custom";

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

Output:

0: Red
1: Green
2: Blue
customProperty: Custom

In this case, customProperty is also included, which may not be intended. For arrays, for loops or for...of loops are better choices.

Using For In with Nested Objects

You can use for...in loops to traverse nested objects, making it easier to work with complex data structures:

let company = {
  name: "TechCorp",
  employees: {
    manager: "Alice",
    developer: "Emma",
    designer: "Sophia"
  }
};

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

Output:

manager: Alice
developer: Emma
designer: Sophia

This allows you to dynamically access each nested property without hardcoding keys.

Checking Own Properties

To avoid inherited properties from the prototype chain, it is best to use the hasOwnProperty method:

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

This ensures that only the object’s own properties are iterated.

Practical Examples

Example 1: Listing Object Keys

let car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2025
};

for (let key in car) {
  console.log("Property name: " + key);
}

Example 2: Summing Numeric Values

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

let total = 0;
for (let subject in scores) {
  total += scores[subject];
}
console.log("Total score: " + total);

Example 3: Modifying Object Properties

let settings = {
  darkMode: false,
  notifications: true
};

for (let key in settings) {
  settings[key] = !settings[key]; // Toggle boolean values
}
console.log(settings);

Example 4: Filtering Properties

let data = {
  name: "Emma",
  age: 25,
  profession: "Developer"
};

for (let key in data) {
  if (typeof data[key] === "string") {
    console.log(key + ": " + data[key]);
  }
}

This loop only logs properties that have string values.

Example 5: Combining With Functions

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

let book = {
  title: "JavaScript Guide",
  author: "Emma",
  pages: 300
};

printObject(book);

Common Mistakes

  • Using for...in for arrays without considering inherited or non-numeric properties.

  • Forgetting to filter with hasOwnProperty() for object prototypes.

  • Modifying the object while iterating without caution, which can cause unexpected results.

  • Confusing for...in with for...of, which is designed for iterable objects like arrays and strings.

Best Practices

  • Use for...in primarily for objects, not arrays.

  • Always check hasOwnProperty() to avoid prototype properties.

  • Keep iterations clean and avoid side effects that change the object structure.

  • Combine with functions for reusable and modular code.

  • Prefer for...of or array methods for arrays and iterable objects.

Real-World Applications

  • Traversing configuration objects to apply settings dynamically.

  • Iterating over API responses that return key-value pairs.

  • Processing nested objects in data structures for web applications.

  • Dynamically generating HTML content based on object properties.

  • Logging, debugging, or transforming object data efficiently.

Summary of JS Loop For In

The for...in loop is a specialized JavaScript loop designed for iterating over object properties. It allows dynamic access to keys and values, making it ideal for objects and key-value data structures. By using hasOwnProperty to filter inherited properties and avoiding its use with arrays, developers can leverage for...in safely and effectively. Understanding this loop is essential for handling dynamic objects, nested data, and real-world applications where object properties need to be accessed programmatically.


Practice Questions

Q1. How do you loop through all properties of a JavaScript object using for...in?

Q2. What variable does the for...in loop assign in each iteration?

Q3. How can you print both the key and the value in a for...in loop?

Q4. What is the output of looping through an object with 3 properties using for...in?

Q5. Is it recommended to use for...in for arrays? Why or why not?

Q6. How do you check if a property belongs directly to an object inside a for...in loop?

Q7. Can for...in loop iterate over inherited properties?

Q8. How do you loop through a nested object using for...in?

Q9. How can you collect all keys of an object into an array using for...in?

Q10. Write a for...in loop that sums all numeric values in an object.


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top