Detailed Explanation of the Difference Between for...in and for...of in JavaScript
- 419Words
- 2Minutes
- 27 Aug, 2024
In JavaScript, for...in
and for...of
are two common looping statements. Although their syntax is similar, their use cases and functionality are different. This article will explore the differences between these two loops and provide examples to help you better understand when to use them.
1. for...in
for...in
is mainly used to iterate over the enumerable properties of an object, i.e., the object’s keys (property names). It will iterate over both the object’s own properties and inherited properties, which is why it’s commonly used for handling regular objects.
Example:
1const obj = { a: 1, b: 2, c: 3 };2
3for (const key in obj) {4 console.log(key); // Outputs a, b, c5}
-
Features:
for...in
iterates over the object’s keys (property names or array indices).- It iterates over all enumerable properties of the object, including inherited ones.
- The iteration order is not guaranteed to match the insertion order, so it’s not suitable for scenarios where order matters.
-
Usage Scenarios:
- Iterating over an object’s properties.
- Not recommended for iterating over arrays, as
for...in
only iterates over indices and the order is not guaranteed.
2. for...of
for...of
is used to iterate over the iterable objects (such as arrays, strings, Map, Set, etc.). Unlike for...in
, for...of
focuses on the values of the object rather than the keys, making it more suitable for handling arrays, strings, and other iterable objects.
Example:
1const arr = [1, 2, 3];2
3for (const value of arr) {4 console.log(value); // Outputs 1, 2, 35}
-
Features:
for...of
iterates over the values of an iterable object.- Suitable for all iterable objects such as arrays, strings, Set, Map, etc.
- Not suitable for regular objects, as they are not iterable.
-
Usage Scenarios:
- Iterating over the values of arrays, strings, Set, Map, and other iterable objects.
- Not suitable for iterating over object properties.
Summary of Differences
-
Different Iteration Targets:
for...in
iterates over the object’s keys (property names or indices).for...of
iterates over the values of an iterable object.
-
Different Applicable Objects:
for...in
is suitable for iterating over object properties and can also iterate over array indices (though not recommended).for...of
is suitable for iterating over iterable objects like arrays, strings, Map, Set, etc.
Example Comparison
1const arr = ["a", "b", "c"];2
3// for...in iterates over the indices (keys)4for (const index in arr) {5 console.log(index); // Outputs 0, 1, 26}7
8// for...of iterates over the values9for (const value of arr) {10 console.log(value); // Outputs 'a', 'b', 'c'11}
Recommendations
- If you need to iterate over the properties of an object, it is recommended to use
for...in
. - If you need to iterate over the values of an array or other iterable objects, it is recommended to use
for...of
.