Introduction
In JavaScript, both for...of
and for...in
are loops that help you iterate
through collections, but they have key differences. Understanding these differences will help you choose
the right loop for your specific task.
1. for...of
Loop
The for...of
loop iterates over the values of iterable objects like arrays,
strings, Maps, and Sets.
Example 1: Array
const fruits = ['Apple', 'Banana', 'Cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
// Output: Apple, Banana, Cherry
Example 2: String
const greeting = 'Hello';
for (const char of greeting) {
console.log(char);
}
// Output: H, e, l, l, o
Example 3: Map
const countries = new Map();
countries.set('IN', 'India');
countries.set('USA', 'United States');
for (const [key, value] of countries) {
console.log(`${key}: ${value}`);
}
// Output: IN: India, USA: United States
2. for...in
Loop
The for...in
loop iterates over the keys of an object or the indices of an
array.
Example 1: Object
const person = { name: 'John', age: 30, city: 'New York' };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output: name: John, age: 30, city: New York
Example 2: Array
const numbers = [10, 20, 30];
for (const index in numbers) {
console.log(index, numbers[index]);
}
// Output: 0 10, 1 20, 2 30
Key Differences
Feature | for...of |
for...in |
---|---|---|
Iterates Over | Values of iterable objects | Keys/indices of an object or array |
Suitable For | Arrays, strings, Maps, Sets | Objects, arrays (not recommended) |
Use Case | Iterating over values of arrays/sets | Iterating over object properties |
Example Showing Difference
const arr = [10, 20, 30];
for (const value of arr) {
console.log(value); // Iterates over values: 10, 20, 30
}
for (const index in arr) {
console.log(index); // Iterates over indices: 0, 1, 2
}
Conclusion
Use for...of
when you need to iterate over values (like arrays, strings, or
Maps). Use for...in
when you need to iterate over keys or properties of
objects.