The Difference Between for...in And for...of in JavaScript
Do you know the difference between the for...in
and for...of
operator in JavaScript? Both of them are used for loops, but they are not the same. Let's see the use of for...in
first.
for...in
The for...in
statement in JavaScript is used for iterating over the enumerable properties (properties whose enumerable flag is set to true
) of an object. This also includes inherited properties. In plain English, this means we can use this statement to loop through the keys of an object in the following way:
const flowers = {
hibiscus: 'πΊ',
sunflower: 'π»',
tulip: 'π·'
};
for (const flower in flowers) {
console.log(`${flower}: ${flowers[flower]}`);
};
// This will log out:
hibiscus: πΊ
sunflower: π»
tulip: π·
for...of
The for...of
statement is used for iterating over iterable objects, such as strings, arrays or array-like objects, for example, maps and sets. It cannot be used with objects. It is essentially, a simplified and more reliable version of a regular for
loop, for looping through arrays:
const phases = ['π', 'π', 'π'];
for (const phase of phases) {
console.log(phase);
};
// This will log out:
π
π
π
Note that you can't use for...of
with objects, as it is not iterable. Another common use-case of for...of
is for looping through a NodeList
:
for (const paragraph of document.querySelectorAll('p')) {
console.log(paragraph);
}
In summary:
- use
for...in
for enumerable properties - use
for...of
for iterable objects
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: