Hiprup

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

Both are loops, but they iterate over different things.

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

  • for...of — iterates over values of any iterable (arrays, strings, Maps, Sets). Meant for collections.

Rule of thumb: for...of for arrays and values, for...in for object keys (or use Object.keys).

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

// for...of — iterates VALUES
for (const value of arr) {
  console.log(value);  // 'a', 'b', 'c'
}

// for...in — iterates KEYS (indices for arrays)
for (const key in arr) {
  console.log(key);    // '0', '1', '2' (strings!)
}

// for...in with objects
const user = { name: 'John', age: 30 };
for (const key in user) {
  console.log(`${key}: ${user[key]}`);  // 'name: John', 'age: 30'
}

// for...of with Map
const map = new Map([['a', 1], ['b', 2]]);
for (const [key, value] of map) {
  console.log(`${key}: ${value}`);  // 'a: 1', 'b: 2'
}

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

// for...in includes prototype properties!
Array.prototype.customMethod = function() {};
for (const key in arr) {
  console.log(key);  // '0', '1', '2', 'customMethod' — oops!
}

for...of gives values directly ('a', 'b', 'c'). for...in gives string keys ('0', '1', '2'). for...in on objects gives property names. for...of works with Map, Set, String. The prototype pollution example shows why for...in on arrays is dangerous — it includes inherited properties.

for...in = keys (objects), for...of = values (iterables). for...in on arrays is dangerous (includes prototype properties). The prototype pollution example is the key gotcha.

Prefer for...of or forEach for arrays, for...in or Object.entries for objects.

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