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

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Feb 21, 2020, updated Oct 12, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-for-of-vs-for-in

> A short guide to learn the difference between for...of and for...in statements in JavaScript and what you should use.

There are multiple ways to iterate through [objects](https://attacomsian.com/blog/javascript-iterate-objects), [arrays](https://attacomsian.com/blog/javascript-loops), and [DOM elements](https://attacomsian.com/blog/javascript-loop-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`](https://attacomsian.com/blog/for-in-loop-in-javascript) statement iterates over all enumerable properties of an [object](https://attacomsian.com/blog/javascript-iterate-objects) including the [inherited](https://attacomsian.com/blog/javascript-own-inherited-properties) enumerable properties in no particular order:

```javascript
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:

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

## `for...of` Loop

The [`for...of`](https://attacomsian.com/blog/javascript-for-of-loop) 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:

```javascript
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!
