JavaScript provides the for...in and for...of loops to iterate over data, but they serve different purposes. The for...in loop iterates over enumerable property keys of an object, while the for...of loop iterates over values produced by an iterable, such as an array, string, or Map. Understanding their differences helps developers choose the correct loop for objects, arrays, and other data structures.
Table of Contents
What Is a for...in Loop in JavaScript?
The for...in loop iterates over the enumerable property keys of an object. It is commonly used when you need to access the names of an object's properties rather than their values directly.
Example:
// JavaScript program to display object property keys using for...in
const student = {
name: "Tanavi",
age: 20,
course: "BSc IT"
};
for (const key in student) {
console.log(key);
}
Output:
name
age
course
In this example, the for...in loop assigns each enumerable property key to the variable key. You can access the corresponding value using student[key].
Example: Display property keys and values.
// JavaScript program to display object keys and values using for...in
const student = {
name: "Tanavi",
age: 20,
course: "BSc IT"
};
for (const key in student) {
console.log(key + ": " + student[key]);
}
Output:
name: Tanavi
age: 20
course: BSc IT
The expression student[key] retrieves the value associated with the current property key.
What Is a for...of Loop in JavaScript?
The for...of loop iterates over the values produced by an iterable object. It is commonly used with arrays, strings, sets, maps, and other objects that implement the iterable protocol.
Example:
// JavaScript program to display array values using for...of
const fruits = ["Apple", "Banana", "Mango"];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
Apple
Banana
Mango
In this example, the for...of loop assigns each array element to the variable fruit. Unlike for...in, it provides the values directly instead of the array's property keys.
Example: Iterate over a string.
// JavaScript program to display characters using for...of
const word = "CODE";
for (const character of word) {
console.log(character);
}
Output:
C
O
D
E
A string is iterable, so for...of can process its characters one at a time.
Syntax of for...in and for...of Loops
Syntax of the for...in loop:
// Syntax of a for...in loop in JavaScript
for (const key in object) {
// Statements to execute
}
The loop assigns each enumerable property key of the object, including eligible inherited enumerable properties, to the variable key.
Syntax of the for...of loop:
// Syntax of a for...of loop in JavaScript
for (const value of iterable) {
// Statements to execute
}
The loop obtains values from the iterable. The iterable must support the iterable protocol; otherwise, JavaScript throws a TypeError.
Examples of for...in and for...of Loops
Example 1: Iterate over an array using for...in.
// JavaScript program to display array indexes using for...in
const colors = ["Red", "Green", "Blue"];
for (const index in colors) {
console.log(index);
}
Output:
0
1
2
For an ordinary array, for...in generally returns its enumerable index keys as strings. It can also include other enumerable properties, so it is not usually the preferred loop for processing array elements.
Example 2: Iterate over an array using for...of.
// JavaScript program to display array values using for...of
const colors = ["Red", "Green", "Blue"];
for (const color of colors) {
console.log(color);
}
Output:
Red
Green
Blue
The for...of loop retrieves each array value directly, making it a suitable choice for processing array elements.
Example 3: Iterate over an object using for...in.
// JavaScript program to display object properties using for...in
const employee = {
name: "Amit",
department: "IT",
experience: 2
};
for (const key in employee) {
console.log(`${key}: ${employee[key]}`);
}
Output:
name: Amit
department: IT
experience: 2
This loop visits the object's enumerable property keys and uses bracket notation to retrieve their values.
Example 4: Iterate over a Set using for...of.
// JavaScript program to iterate over a Set using for...of
const numbers = new Set([10, 20, 30]);
for (const number of numbers) {
console.log(number);
}
Output:
10
20
30
A Set is iterable, so for...of retrieves its values in insertion order.
Example 5: Iterate over a Map using for...of.
// JavaScript program to iterate over Map entries using for...of
const studentMarks = new Map([
["Maths", 85],
["Science", 90]
]);
for (const [subject, marks] of studentMarks) {
console.log(`${subject}: ${marks}`);
}
Output:
Maths: 85
Science: 90
By default, a Map iterator produces key-value pairs. Array destructuring allows each pair to be assigned to subject and marks.
Difference Between for...in and for...of
Both loops simplify iteration, but they work with different kinds of information.
| Feature | for...in | for...of |
|---|---|---|
| Main purpose | Iterates over enumerable property keys | Iterates over values from an iterable |
| Returned item | Property key, usually a string | Value produced by the iterator |
| Common use | Objects | Arrays, strings, sets, and maps |
| Works directly with ordinary objects | Yes, for enumerable properties | No, unless the object is iterable |
| Array behavior | Iterates over enumerable keys, including possible extra properties | Iterates over array values |
| String behavior | Iterates over enumerable index keys | Iterates over string characters |
| Inherited properties | Can include inherited enumerable properties | Depends on the iterable's iterator |
| Iteration order | Follows JavaScript property-enumeration rules | Follows the iterable's iteration order |
| Best suited for | Inspecting object property names | Processing values in an iterable |
Key difference: Use for...in when you need property keys, and use for...of when you need values from an iterable.
Using for...in with Objects
The for...in loop is useful for inspecting an object's enumerable properties. However, it can include enumerable properties inherited through the prototype chain.
If you only want an object's own enumerable properties, use Object.hasOwn() to filter out inherited properties.
Example:
// JavaScript program to iterate over an object's own properties
const person = {
name: "Riya",
age: 21
};
for (const key in person) {
if (Object.hasOwn(person, key)) {
console.log(`${key}: ${person[key]}`);
}
}
Output:
name: Riya
age: 21
The Object.hasOwn(person, key) check ensures that only properties belonging directly to person are processed.
For many object-processing tasks, Object.keys(), Object.values(), or Object.entries() may also be useful alternatives.
Using for...of with Arrays and Strings
The for...of loop is useful when you need to process the values of an iterable without manually managing an index.
Example:
// JavaScript program to calculate the total of array values
const prices = [100, 200, 150];
let total = 0;
for (const price of prices) {
total += price;
}
console.log("Total:", total);
Output:
Total: 450
Each array value is added to total during iteration.
Example:
// JavaScript program to count characters in a string
const message = "Hello";
let count = 0;
for (const character of message) {
count++;
}
console.log("Characters:", count);
Output:
Characters: 5
The for...of loop processes each string iteration value. For strings containing certain Unicode characters, such as emoji, this counts Unicode code points rather than UTF-16 code units or user-perceived grapheme clusters.
When to Use for...in and for...of
Choose the loop based on the type of data and what you need to access.
Use for...in when:
- You need to inspect an object's property keys.
- You want to process enumerable properties.
- You need to access object values using their keys.
- You are working with plain objects and understand inherited-property behavior.
Use for...of when:
- You need to process array elements.
- You want to iterate over characters in a string.
- You are working with a Set or Map.
- You need values from another iterable, such as a generator.
- You want to use break or continue to control iteration.
Example: Choosing the correct loop.
// JavaScript program to compare property keys and array values
const numbers = [10, 20, 30];
console.log("Using for...in:");
for (const key in numbers) {
console.log(key);
}
console.log("Using for...of:");
for (const value of numbers) {
console.log(value);
}
Output:
Using for...in:
0
1
2
Using for...of:
10
20
30
This example demonstrates the difference clearly: for...in retrieves the array's property keys, while for...of retrieves its values.
Common Mistakes to Avoid
-
Using for...in to process array values: The loop returns property keys rather than array elements. Use for...of when you need the values.
-
Using for...of with a non-iterable object: A plain object is not iterable by default. Use for...in, Object.keys(), or Object.entries() to inspect its properties.
-
Assuming for...in returns only own properties: It can include inherited enumerable properties. Use Object.hasOwn() when you need to filter them.
-
Confusing array indexes with values: In a for...in loop, array indexes are typically returned as strings, whereas for...of provides the elements themselves.
-
Modifying a collection without considering iteration behavior: Adding, deleting, or changing properties during iteration can affect what gets visited. Understand the relevant object's iteration rules before modifying it.
Frequently Asked Questions
1. What is the main difference between for...in and for...of in JavaScript?
The for...in loop iterates over enumerable property keys, while the for...of loop iterates over values produced by an iterable.
2. Can for...in be used with arrays?
Yes. It can iterate over an array's enumerable property keys, but for...of is generally better when you need the array's elements.
3. Can for...of be used with objects?
A plain object is not iterable by default. You can use Object.entries(object) with for...of to iterate over its key-value pairs.
4. Which loop is better for iterating over a JavaScript object?
Use for...in when you need enumerable property keys. If you only want an object's own properties, filter with Object.hasOwn() or use methods such as Object.keys() and Object.entries().
5. Does for...of return array indexes?
No. The for...of loop returns array values. To access both an index and its value, use array.entries() with for...of.
0 Comments