Difference Between
for..in and for..of
for..in
Purpose
Iterating over the enumerable properties of an object. This includes properties on the object itself and properties inherited through its prototype chain.
Syntax
When to use
- You need to work with the property names (keys) of an object.
- The order of iteration is not critically important.
for..of
Purpose
Iterating directly over the values of an iterable object. Iterables include:
- Arrays
- Strings
- Maps
- Sets
- NodeList
- Some other built-in objects
Syntax
When to use
- You want to work directly with the values of an array, string, or other iterable.
- The order of iteration matters.
Key Points and Considerations
- Enumerability:
for...in
loops over enumerable properties. A property is enumerable if it shows up when iterating over the object's properties. - Iterables:
for...of
is specifically designed for iterable objects—objects that implement the iterable protocol. - Performance:
for...of
is often slightly faster thanfor...in
especially in modern JavaScript engines, as it doesn't need to perform property lookups on each iteration. - Don't Modify During
for...in
: Avoid modifying the object you're iterating over within afor...in
loop, as it can lead to unexpected behavior due to how enumerable properties are determined.
Example
To Summarize
for...in
: Object properties (best for plain objects)for...of
: Values in arrays, strings, and other iterables.
Last Update: 14:51 - 14 April 2024