In JavaScript, both the
`for...in` and
`for...of` loops are used for iteration, but they serve different purposes and work with different types of data structures. Here's the difference between them:
1. `for...in` loop:
The `for...in` loop is used to iterate over the enumerable properties of an object. It iterates over the keys of an
object and provides access to the property names. Here's the basic syntax:
for (variable in object) {
// code to be executed
}
The `variable` represents the property name in each iteration. Here's an example:
const obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key); // Outputs: a, b, c
console.log(obj[key]); // Outputs: 1, 2, 3
}
Note that
`for...in` loop can also iterate over the inherited properties of an object. To avoid this, you can use the `hasOwnProperty` method to check if the property is directly defined on the object itself.
2. `for...of` loop:
The `for...of` loop is used to iterate over iterable objects like arrays, strings, sets, maps, etc. It provides access to the values of the elements rather than their indices or keys. Here's the basic syntax:
for (variable of iterable) {
// code to be executed
}
The `variable` represents the value in each iteration. Here's an example:
const arr = [1, 2, 3];
for (let value of arr) {
console.log(value); // Outputs: 1, 2, 3
}
Unlike the
`for...in` loop, the
`for...of` loop does not give you access to the keys or indices of the iterable object. It directly provides the values. It's a simpler and more concise way to iterate over arrays and other iterable objects.
Conclusion:
`for...in` loop is used to iterate over object properties (keys), while the
`for...of` loop is used to iterate over iterable objects, providing access to their values.