How to use the for in loop in JavaScript

Updated onbyAlan Morel
How to use the for in loop in JavaScript

JavaScript gives you many different ways to iterate over an array or object.

Options include the forEach method, the while loop, and a traditional for loop.

But there is another way to iterate that is not as well known: the for...in loop.

In this post, we'll learn how to use the for...in loop to iterate.

How to use the for...in Loop with Objects

To demonstrate how to use the for...in loop, we'll use the following object:

JAVASCRIPT
const object = { a: 1, b: 2, c: 3 };

We can use the for...in loop to iterate over the object's keys:

JAVASCRIPT
const object = { a: 1, b: 2, c: 3 }; for (const key in object) { console.log(key); }
BASH
a b c

Once we have the key, getting the value is easy:

JAVASCRIPT
const object = { a: 1, b: 2, c: 3 }; for (const key in object) { const value = object[key]; console.log("key:", key, "value:", value); }
BASH
key: a value: 1 key: b value: 2 key: c value: 3

How to use the for...in Loop with Arrays

This loop can also be used for arrays.

Instead of returning the key, it returns the index, which can be used to get the value:

JAVASCRIPT
const array = [1, 2, 3]; for (const index in array) { const value = array[index]; console.log("index:", index, "value:", value); }
BASH
index: 0 value: 1 index: 1 value: 2 index: 2 value: 3

Conclusion

In this post, we learned how to use the for...in loop to iterate over an array or object.

You can use this loop to get the keys of an object or the indexes of an array, which you can then use to get the values.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.