Junior
What is the difference between for...in and for...of loops?
sobes.tech AI
Answer from AI
The for...in loop iterates over the keys (properties) of enumerable object properties, including properties in its prototype chain.
The for...of loop iterates over the values of iterable objects (Array, Map, Set, String, arguments, etc.). It does not iterate over prototype properties.
for...in |
for...of |
|
|---|---|---|
| Iterates over | Object keys (properties) | Values of iterable objects |
| Used with | Objects | Arrays, strings, Map, Set, and other iterable objects |
| Prototype | Iterates over prototype properties | Does not iterate over prototype properties |
| Order of traversal | Not guaranteed for non-integer keys | Guaranteed for arrays (by index) |
Example of for...in:
const obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key, obj[key]); // Outputs: "a 1", "b 2"
}
Example of for...of:
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value); // Outputs: 1, 2, 3
}
In general, for iterating over arrays and similar structures, for...of is preferred, while for iterating over object properties, for...in is used (often in conjunction with hasOwnProperty to exclude prototype properties).