Difference between for...of and for...in loops in JavaScript

In this article 👇

There are multiple ways to iterate through objects, arrays, and DOM elements in JavaScript. Traditionally, the basic for loop was used to perform an iteration. But, lately, the other iteration methods have become more popular.

In this article, I'll describe the difference between the for...of and for...in statements, two of the most commonly used iteration methods in modern JavaScript. Both these statements are used for looping purposes. The main difference between them is what they iterate over.

for...in Loop

The for...in statement iterates over all enumerable properties of an object including the inherited enumerable properties in no particular order:

const book = {
  title: 'JavaScript for Beginners',
  price: '$9.99',
  year: 2018,
  pubisher: 'Amazon, Inc.'
}

// iterate over the object
for (const key in book) {
  console.log(`${key} --> ${book[key]}`)
}

// title --> JavaScript for Beginners
// price --> $9.99
// year --> 2018
// pubisher --> Amazon, Inc.

To skip the object inherited properties, just use the hasOwnProperty() method:

for (const key in book) {
  if (book.hasOwnProperty(key)) {
    console.log(`${key} --> ${book[key]}`)
  }
}

for...of Loop

The for...of statement loops over the values of iterable objects like arrays, strings, maps, sets, NodeLists, and similar. It doesn't work for objects because they are not iterable.

Here is an example:

const names = ['Alex', 'Emma', 'Atta', 'John']

// iterate over names
for (const name of names) {
  console.log(`Hey ${name}!`)
}

// Hey Alex!
// Hey Emma!
// Hey Atta!
// Hey John!

Rule of Thumb: Always use the for...in loop to iterate over objects. For all kinds of iterable objects in JavaScript, for...of is the way to go!

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.