Table of Contents
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:
JAVASCRIPTconst object = {
a: 1,
b: 2,
c: 3
};
We can use the for...in loop to iterate over the object's keys:
JAVASCRIPTconst object = {
a: 1,
b: 2,
c: 3
};
for (const key in object) {
console.log(key);
}
BASHa
b
c
Once we have the key, getting the value is easy:
JAVASCRIPTconst object = {
a: 1,
b: 2,
c: 3
};
for (const key in object) {
const value = object[key];
console.log("key:", key, "value:", value);
}
BASHkey: 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:
JAVASCRIPTconst array = [1, 2, 3];
for (const index in array) {
const value = array[index];
console.log("index:", index, "value:", value);
}
BASHindex: 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!
- Support Us
Share Post Share
Getting Started with TypeScript
Getting Started with Svelte
Getting Started with Express
Create an RSS Reader in Node
Git Tutorial: Learn how to use Version Control
How to Set Up Cron Jobs in Linux
How to deploy a MySQL Server using Docker
Learn how to use v-model with a custom Vue component
Getting User Location using JavaScript's Geolocation API
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with React
Using Axios to Pull Data from a REST API
