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!
- Getting Started with Express
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with React