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
How to Install Node on Windows, macOS and Linux
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
How to deploy a .NET app using Docker
How to build a Discord bot using TypeScript
How to Scrape the Web using Node.js and Puppeteer
Learn how to build a Slack Bot using Node.js
Getting Started with React
Setting Up Stylus CSS Preprocessor
Getting Started with Vuex: Managing State in Vue
