August 13, 2021

for…in vs for…of in JavaScript β€” Simple Explanation


βœ… What is for...in?

for...in loops over keys (property names) in an object or array.

πŸ§ͺ Example:

const obj = { a: 1, b: 2, c: 3 };

for (let key in obj) {
  console.log(key);        // a, b, c
  console.log(obj[key]);   // 1, 2, 3
}

πŸ§ͺ In arrays:

const arr = ['x', 'y', 'z'];
for (let index in arr) {
  console.log(index);   // 0, 1, 2
  console.log(arr[index]); // x, y, z
}

🟑 Note: for...in gives index, not values for arrays.


βœ… What is for...of?

for...of loops over values of iterable objects (like arrays, strings, maps, sets).

πŸ§ͺ Example with array:

const arr = ['x', 'y', 'z'];
for (let value of arr) {
  console.log(value); // x, y, z
}

πŸ§ͺ Example with string:

for (let char of 'hello') {
  console.log(char); // h, e, l, l, o
}

🟒 for...of is not for plain objects, unless you use Object.entries() or similar.


βš–οΈ Comparison Table

Featurefor...infor...of
Iterates overProperty keys (names)Property values
Works on objectsβœ… Yes❌ No (unless iterable)
Works on arraysβœ… Yes (indexes)βœ… Yes (values)
Output for arrayIndexes: 0, 1, 2...Values: 'a', 'b', 'c'...
Use caseLoop through object keysLoop through values of array, string, map, set

πŸ’‘ When to Use

You want to…Use
Loop over object propertiesfor...in
Loop over array valuesfor...of
Loop over string charactersfor...of
Loop over Map / Set valuesfor...of
Loop over array indexes manuallyfor...in

⚠️ Important Notes

  • for...in can loop over inherited properties, so it’s best with hasOwnProperty(): jsCopyEditfor (let key in obj) { if (obj.hasOwnProperty(key)) { // safe to use } }
  • for...of only works on iterable objects.

βœ… Summary

for...in = loop over keys (property names)
for...of = loop over values


🧠 One-line answer for interviews:

for...in is for object keys, for...of is for iterable values like arrays or strings.”