The Difference Between for...in And for...of in JavaScript

The Difference Between for...in And for...of in JavaScript

Ferenc Almasi β€’ 2020 October 13 β€’ Read time 2 min read
  • twitter
  • facebook
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:

Copied to clipboard! Playground
const flowers = {
    hibiscus: '🌺',
    sunflower: '🌻',
    tulip: '🌷'
};

for (const flower in flowers) {
    console.log(`${flower}: ${flowers[flower]}`);
};

// This will log out:
hibiscus: 🌺
sunflower: 🌻
tulip: 🌷
for-in.js

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:

Copied to clipboard! Playground
const phases = ['🌘', 'πŸŒ—', 'πŸŒ–'];

for (const phase of phases) {
    console.log(phase);
};

// This will log out:
🌘
πŸŒ—
πŸŒ–
for-of.js

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:

Copied to clipboard!
for (const paragraph of document.querySelectorAll('p')) {
    console.log(paragraph);
}
for-of.js

In summary:

  • use for...in for enumerable properties
  • use for...of for iterable objects
The Difference Between for...in And for...of in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.