Hiprup

What is the difference between for...in and for...of?

Both are loops, over different things.

  • for...in — iterates keys (property names), including inherited ones. For objects.

  • for...of — iterates values of iterables (arrays, strings, Maps, Sets). For collections.

Rule of thumb: for...of for array values, for...in for object keys.

const arr = ['a', 'b', 'c'];

for (const key in arr) console.log(key);    // '0', '1', '2' (string keys)
for (const val of arr) console.log(val);    // 'a', 'b', 'c' (values)

const obj = { x: 1, y: 2 };
for (const key in obj) console.log(key);    // 'x', 'y'
// for (const val of obj) {} // TypeError! Objects are not iterable

// Use Object.entries for for...of on objects
for (const [key, val] of Object.entries(obj)) {
  console.log(key, val); // 'x' 1, 'y' 2
}

for...in gives string keys ('0', '1', '2' for arrays). for...of gives values ('a', 'b', 'c'). Objects work with for...in but not for...of (not iterable).

Object.entries converts objects to iterables for for...of.

for...in = keys (objects), for...of = values (iterables). for...in on arrays gives string indices (not recommended — use for...of). Object.entries for iterating objects with for...of. for...in includes prototype properties.

What is the difference between for...in and for...of? | Hiprup