JavaScript provides two specialized loops to iterate over collections and objects: for...of and for...in. Understanding when and how to use each is essential for effective coding.

💡 Purpose Distinction
for...of iterates over iterable values (like arrays, strings, maps), while for...in iterates over the enumerable property keys of an object.
for...of and for...in| Aspect | for...of | for...in |
|---|---|---|
| Iterates Over | Values of iterable objects (arrays, strings, sets, maps) | Keys (property names) of an object (including arrays) |
| Use Case | When you need the actual elements or values | When you need the property keys or indexes |
| Applicable To | Iterable objects only | Any object with enumerable properties |
| Order Guarantee | Preserves the order of elements | Order is not guaranteed, especially in objects |
Using for...of
The for...of loop extracts the values directly from iterable objects.
📌 Deep Dive: Looping Over an Array with for...of
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
banana
cherry
Using for...in
The for...in loop iterates over enumerable keys (property names) of an object or indexes of an array.
📌 Deep Dive: Looping Over Object Properties with for...in
const person = {
name: 'Alice',
age: 25,
city: 'Wonderland'
};
for (const key in person) {
console.log(key + ': ' + person[key]);
}
age: 25
city: Wonderland
⚠️ Caution When Using for...in with Arrays
Using for...in on arrays iterates over indexes as strings, including inherited enumerable properties, which can cause unexpected behavior. Prefer for...of for arrays.
Summary
for...of— Use to get values from iterable data structures (arrays, strings).for...in— Use to get keys or property names from objects.- For arrays,
for...ofis usually the better choice.
💡 Extra Tip
Strings are iterable, so for...of can loop through each character:
📌 Deep Dive: Looping Over a String
const greeting = 'Hi!';
for (const char of greeting) {
console.log(char);
}
i
!
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which loop should you use to iterate over the values in an array?
Question 2 of 2
What does a for...in loop iterate over when used on an object?
Loading results...