How to use for...in loop in JavaScript

The for...in loop iterates through the properties of an object in JavaScript. The loop iterates over all enumerable properties of the object itself and those inherited from its prototype chain.

How for...in works?

for (const key in object) {
    // do something
}

The key is the variable name assigned a different property name on each iteration. The object is the actual iterable (object literals, array, strings) you are looping over. The block of code inside the loop is executed once for each property.

You can use the key to obtain the property value from the object.

Here is an example:

const user = {
  name: 'John Doe',
  email: 'john.doe@example.com',
  age: 25,
  admin: false
}

for (const key in user) {
  console.log(key) // property name
  console.log(user[key]) // property value
}

for...in loop examples

Let us have some more examples. The following for...in loop iterates through the properties of an object literal and logs a string of the property names and their values:

const animals = {
  tiger: '🐅',
  cat: '🐱',
  monkey: '🐒',
  horse: '🐴',
  elephant: '🐘'
}

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

// tiger --> 🐅
// cat --> 🐱
// monkey --> 🐒
// horse --> 🐴
// elephant --> 🐘

You can also use for...in to loop through an array or a string by using their index values:

const str = 'JavaScript Loops'

for (const index in str) {
  console.log(`${str[index]} is at ${index} index.`)
}

// J is at 0 index.
// a is at 1 index.
// v is at 2 index.
// a is at 3 index.
// ...

According to MDN, the for...in loop should not be used to iterate over an array where the index order is important. This loop does not guarantee to return the indexes in the original order. Instead, you should use a simple for loop with a numeric index or for...of loop when iterating over arrays where the order of access is important.

for...in loop and prototypes

Objects in JavaScript can have properties inherited from object prototypes.

For example, objects created using Array and Object constructors inherit many properties from Object.prototype and String.prototype. The for...in statement iterates over own properties of the object itself and those the object inherits from its constructor's prototype.

Let us have an example to understand this inheritance:

function Animal(name, icon) {
  this.name = name
  this.icon = icon
}

const cat = new Animal('Cat', '🐱')

Animal.prototype.color = 'White'

for (const prop in cat) {
  console.log(`Aminal ${prop} is ${cat[prop]}.`)
}

// Aminal name is Cat.
// Aminal icon is 🐱.
// Aminal color is White.

The color of the animal is part of the prototype and not the actual object cat but is returned anyways. If you are only interested in properties that are attached to the object itself and not its prototypes, use the hasOwnProperty() method to ensure that the key is a property of the actual object:

for (const prop in cat) {
  if (cat.hasOwnProperty(prop)) {
    console.log(`Aminal ${prop} is ${cat[prop]}.`)
  }
}

It is better to always perform the hasOwnProperty() check in a for...in loop unless you explicitly want to iterate through properties inherited from object prototypes.

Browser compatibility

The for...in loop works perfectly in all modern browsers, including Internet Explorer 6 and higher.

✌️ 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.