In JavaScript, both for...in
and for...of
loops are used for iteration, but they have different purposes and behaviors:
for...in
Loop:
-
The
for...in
loop iterates over the enumerable properties of an object, including inherited properties from its prototype chain. - It is commonly used for iterating over the keys (property names) of an object.
- It should not be used to iterate over arrays, as it may iterate over non-index properties and does not guarantee the order of iteration.
-
Example:
const obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key); // Outputs: 'a', 'b', 'c'
}
for...of
Loop:
-
The
for...of
loop iterates over the iterable objects, such as arrays, strings, maps, sets, etc., and it iterates over their values, not their keys. - It is commonly used for iterating over the values of arrays or other iterable objects.
- It cannot be used to iterate over regular objects directly, as they are not iterable unless they implement the iterable protocol.
-
Example:
const arr = [1, 2, 3];
for (let value of arr) {
console.log(value); // Outputs: 1, 2, 3
}