Codectionary / Developer documentation / JavaScript

for...in vs for...of

for...in iterates over the enumerable property keys of an object (or the indices of an array, though this is discouraged). for...of iterates over the values of an iterable, like arrays, strings, Maps, and Sets - it is generally the better choice when working with arrays.

Syntax

for (const key in object) { }
for (const value of iterable) { }

Examples

for...in with Objects

Iterating over an object's property keys.

const user = { name: "Alice", age: 25, city: "London" };

for (const key in user) {
  console.log(`${key}: ${user[key]}`);
}
// name: Alice
// age: 25
// city: London

for...of with Arrays

Iterating over array values directly - the preferred way to loop over arrays.

const colors = ["red", "green", "blue"];

for (const color of colors) {
  console.log(color);
}
// red, green, blue

// Also works with strings, Maps, and Sets
for (const char of "abc") {
  console.log(char); // a, b, c
}

Best practices

  • Use for...of for arrays and other iterables - it gives you values directly without needing an index
  • Use for...in only for plain objects, and be aware it also picks up inherited enumerable properties unless filtered
  • Avoid for...in on arrays - it iterates over string keys (including inherited ones) and does not guarantee order the way for...of does
  • Prefer Object.keys()/values()/entries() combined with for...of or forEach() as an often clearer alternative to for...in

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation