-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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.
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.
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.
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.
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.
let car = {
brand: "Toyota",
model: "Corolla",
year: 2025
};
for (let key in car) {
console.log("Property name: " + key);
}
let scores = {
math: 90,
science: 80,
english: 85
};
let total = 0;
for (let subject in scores) {
total += scores[subject];
}
console.log("Total score: " + total);
let settings = {
darkMode: false,
notifications: true
};
for (let key in settings) {
settings[key] = !settings[key]; // Toggle boolean values
}
console.log(settings);
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.
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);
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.
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.
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.
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.
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.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
