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: Londonfor...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
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification