JavaScript(JS) for...of Vs for...in
In JavaScript, both for...of
and for...in
loops are used for iteration, but they differ in their use cases.
The for...of
loop is used to iterate over the values of an iterable object such as an array, a string, or a Map
. It provides a simple way to loop through the elements of an iterable object and perform an action on each element. Here's an example that demonstrates how to use the for...of
loop to iterate over the elements of an array:
let numbers = [1, 2, 3, 4, 5]; for (let number of numbers) { console.log(number); }
The for...in
loop, on the other hand, is used to iterate over the properties of an object. It allows you to loop through the keys of an object and perform an action on each property. Here's an example that demonstrates how to use the for...in
loop to iterate over the properties of an object:
let person = { name: 'John', age: 30, city: 'New York' }; for (let property in person) { console.log(property + ': ' + person[property]); }
One important thing to note is that the for...in
loop should not be used to iterate over the elements of an array. Instead, you should use a for
loop or a forEach
method. If you use a for...in
loop with an array, you'll iterate over not only the elements of the array but also any properties that have been added to the array object.
In summary, the for...of
loop is used to iterate over the values of an iterable object, while the for...in
loop is used to iterate over the properties of an object.