The for...in
and for...of
loops are two loops specifically designed to iterate through objects and collections of data.
Although the syntax is quite similar, each has its own purpose and characteristics (they actually have quite a few differences).
for...in
iterates over the keys.for...of
iterates over the values.
for...in
Loop
The for...in
loop is used to iterate over the enumerable properties of an object. The syntax is as follows:
for (const key in object) {
// Code block
}
- key: A variable that represents the key of each property of the object in each iteration.
- object: The object whose properties will be iterated.
Let’s see it with an example:
const person = {
name: 'Luis',
age: 30
};
// `for...in` loops through the keys of the object
for (const key in person) {
console.log(`Key: ${key}, Value: ${person[key]}`);
}
// Key: name, Value: Luis
// Key: age, Value: 30
- Iterates over enumerable properties:
for...in
iterates over the enumerable properties of the object (including properties inherited from the prototype chain). - Order of iteration: The order in which properties are iterated is not guaranteed.
for...of
Loop
The for...of
loop is used to iterate over the values of iterable objects (such as arrays, strings, maps), sets, and other types of collections. The syntax is as follows:
for (const value of iterable) {
// Code block
}
- value: A variable that represents the value of each element in the iterable object in each iteration.
- iterable: The iterable object whose values will be iterated.
For example, this is how it would work with an array:
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number);
}
// Output:
// 1
// 2
// 3
// 4
// 5
- Iteration over values: Iterates over the values of an iterable object.
- Order of iteration: Iterates in the natural order of the elements in the iterable.
- Non-iterable: cannot be used directly with non-iterable objects, (such as regular literal objects)
Comparison between for...in
and for...of
To understand the difference between for...in
and for...of
, let’s see an example:
const colors = ['red', 'green', 'blue'];
// `for...in` will iterate over the keys
for (const index in colors) {
console.log(index); // 0, 1, 2
}
// `for...of` will iterate over the values
for (const color of colors) {
console.log(color); // red, green, blue
}
In this example,
for...in
will iterate over the keys (in this case the indices giving me 0, 1, and 2)for...of
will iterate over the values directly (and will return red, green, blue)
This is because an Array in JavaScript is an object, where the key is the index of the Array.
- Use
for...in
with objects: For literal objects and when you need to iterate over the keys and their values. - Use
for...of
with arrays and other iterables: Preferred for iterating over arrays, strings, and other iterable objects.