Back to Blog

for...of vs for...in in JavaScript

When to use each loop

3 min read
  • JavaScript
  • for...of
  • for...in

When iterating over objects in JavaScript, it’s important to know the difference between for...of and for...in.

for…of

  • Used for iterable objects: arrays, strings, Map, or Set.
  • Iterates over values.
  • Does not work with plain objects (throws an error).

Example:

const myMap = new Map([
  ["a", 1],
  ["b", 2],
]);

for (const [key, value] of myMap) {
  console.log(key, value);
}
// Output: a 1, b 2

for…in

  • Used for plain objects.
  • Iterates over keys (property names).
  • Does not work directly with Map or other iterables.

Example:

const myObj = { a: 1, b: 2 };

for (const key in myObj) {
  console.log(key, myObj[key]);
}
// Output: a 1, b 2

Key differences

  • for…of works with iterables (e.g. arrays, Map); for…in is for plain objects.
  • Use Object.entries() if you need to loop through both keys and values of a plain object with for...of.

Knowing when to use each saves you time and avoids errors—simple but effective.