How to use the for in loop in JavaScript
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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Getting User Location using JavaScript's Geolocation API
- Setting Up Stylus CSS Preprocessor
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js