For...of and For...in

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.

Illustration of for_of_and_for_in
Illustration of for_of_and_for_in

💡 Purpose Distinction

for...of iterates over iterable values (like arrays, strings, maps), while for...in iterates over the enumerable property keys of an object.

Key Differences Between for...of and for...in
Aspectfor...offor...in
Iterates OverValues of iterable objects (arrays, strings, sets, maps)Keys (property names) of an object (including arrays)
Use CaseWhen you need the actual elements or valuesWhen you need the property keys or indexes
Applicable ToIterable objects onlyAny object with enumerable properties
Order GuaranteePreserves the order of elementsOrder 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

JAVASCRIPT
const fruits = ['apple', 'banana', 'cherry'];

for (const fruit of fruits) {
  console.log(fruit);
}
Output
apple
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

JAVASCRIPT
const person = {
  name: 'Alice',
  age: 25,
  city: 'Wonderland'
};

for (const key in person) {
  console.log(key + ': ' + person[key]);
}
Output
name: Alice
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...of is usually the better choice.

💡 Extra Tip

Strings are iterable, so for...of can loop through each character:

📌 Deep Dive: Looping Over a String

JAVASCRIPT
const greeting = 'Hi!';

for (const char of greeting) {
  console.log(char);
}
Output
H
i
!