Back to Basics: for…in Loops in JavaScript – SitePoint

Loops allow us to cycle through items in arrays or objects and do things like print them, modify them, or perform other kinds of tasks or actions. There are different kinds of loops in JavaScript, and one of them is the for…in loop.
In this article, we’ll learn about the for…in loop JavaScript provides. We’ll look at how the for…in loop is used in JavaScript, its syntax, examples of how it works, when to use it, when not to use it, and what other types of loops we can use instead.
Why Use Loops
In JavaScript, just as in other programming languages, we use loops to read or access the items of a collection. The collection can be an array or an object. Every pass through the items of a collection is called an iteration.
There are two ways to access an item in a collection. The first way is via its key in the collection, which is an index in an array or a property in an object. The second way is via the item itself, without needing the key.

Definition of the for…in Loop
The JavaScript for…in loop goes through or iterates keys of a collection. Using these keys, you can then access the item it represents in the collection.
The collection of items can be either arrays, objects, or even strings.
Syntax of the for…in Loop
The for…in loop has the following syntax or structure:
for (let key in value) {

}

In this code block, value is the collection of items we’re iterating over. It can be an object, array, string, and so on. key will be the key of each item in value, changing on each iteration to the next key in the list.
Note that we use let or const to declare key.

Using the for…in Loop with Objects
When using for…in loop to iterate an object in JavaScript, the iterated keys or properties — which, in the snippet above, are represented by the key variable — are the object’s own properties.
As objects might inherit items through the prototype chain, which includes the default methods and properties of Objects as well as Object prototypes we might define, we should then use hasOwnProperty.
A for…in loop object example
In the following example, we’re looping over the following variable obj:
const obj = {
1: “JavaScript”,
3: “PHP”,
2: “Python”,
4: “Java”
};

In the loop, we’re rendering the property and value in a

element.

See the Pen Looping Objects by SitePoint (@SitePoint)on CodePen.

Notice that the order of the iteration is ascending for the keys (that is, starting with digits in numerical order and then letters in alphabetical order). However, this outputted order is different from the index order of the items as created when initializing the object.
Using a for…in Loop with Arrays
When using the for…in loop to iterate arrays in JavaScript, key in this case will be the indices of the elements. However, the indices might be iterated in a random order.
So, if the value variable in the for…in loop syntax structure we showed above was an array of five items, key would not be guaranteed to be 0 to 4. Some indices might precede others. Details on when this might happen is explained later in this article.
For…in loop array example
In the example below, we’re looping over the following variable arr:
const arr = [“Javascript”, “PHP”, “Python”, “Java”];

And in the loop, we’re rendering the index and the value of each array element.

See the Pen Looping Arrays by SitePoint (@SitePoint)on CodePen.

Using a for…in Loop with Strings
You can loop over a string with the JavaScript for…in loop. However, it’s not recommended to do so, as you’ll be looping over the indices of the characters rather than the characters themselves.
A for…in loop string example
In the example below, we’re looping over the following variable str:
const str = “Hello, World!”;

Inside the loop, we’re rendering the key, or index of each character, and the character at that index.

See the Pen Strings Loop by SitePoint (@SitePoint)on CodePen.

When to Use a for…in Loop
Let’s look at the situations that the JavaScript for…in loop is best suited to.
Iterating objects with a JavaScript for…in loop
Because the for…in loop only iterates the enumerable properties of an object — which are the object’s own properties rather than properties like toString that are part of the object’s prototype — it’s good to use a for…in loop to iterate objects. A for…in loop provides an easy way to iterate over an object’s properties and ultimately its values.
Debugging with a for…in loop
Another good use case for the JavaScript for…in loop is debugging. For example, you may want to print to the console or an HTML element the properties of an object and its values. In this case, the for…in loop is a good choice.
When using the for…in loop for debugging objects and their values, you should always keep in mind that iterations are not orderly, meaning that the order of items that the loop iterates can be random. So, the order of the properties accessed might not be as expected.
When Not to Use a JavaScript for…in Loop
Now let’s look at situations where a for…in loop isn’t the best option.
Orderly iterating of arrays
As the index order in the iterations is not guaranteed when using the for…in loop, it’s recommended to not iterate arrays if maintaining the order is necessary.
This is especially essential if you’re looking to support browsers like IE, which iterates in the order the items are created rather than in the order of the indices. This is different from the way current modern browsers work, which iterate arrays based on the indices in ascending order.
So, for example, if you have an array of four items and you insert an item into position three, in modern browsers the for…in loop will still iterate the array in order from 0 to 4. In IE, when using a for…in loop, it will iterate the four items that were originally in the array in the beginning and then reach the item that was added at position three.
Making changes while iterating
Any addition, deletion, or modification to properties doesn’t guarantee an ordered iteration. Making changes to properties in a for…in loop should be avoided. This is mostly due to its unordered nature.
So, if you delete an item before you reach it in the iteration, the item will not be visited at all in the entire loop.
Similarly, if you make changes to a property, it doesn’t guarantee that the item won’t be revisited again. So, if a property is changed it might be visited twice in the loop rather than once.
In addition, if a property is added during iteration, it might or might not be visited during the iteration at all.
Due to these situations, it’s best to avoid making any alterations, deletions, or additions to an object in a for…in loop.
Here’s an example of adding an element in a for…in loop. We can see the result of the first loop then the second after making additions in the first loop.

See the Pen Addition in Object Loop by SitePoint (@SitePoint)on CodePen.

As you can see in the above example, the elements that were added weren’t iterated over.
Alternative Loop Types
So in those situations where a for…in loop isn’t the best option, what should you use instead? Let’s take a look.
Using a for loop with arrays
It’s never wrong to use a for loop! The JavaScript for loop is one of the most basic tools for looping over array elements. The for loop allows you to take full control of the indices as you iterate an array.
This means that when using the for loop, you can move forwards and backwards, change items in the array, add items, and more, while still maintaining the order of the array.
The following statement creates a loop that iterates over an array and prints its values to the console.
for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } forEach method for arrays and objects forEach in JavaScript is a method on array prototypes that allows us to iterate over the elements of an array and their indices in a callback function. Callback functions are functions that you pass to another method or function to be executed as part of the execution of that method or function. When it comes to forEach in JavaScript, it means that the callback function will be executed for each iteration receiving the current item in the iteration as a parameter. For example, the following statement iterates over the variable arr and prints its values in the console using forEach: arr.forEach((value) => console.log(value));

You can also access the index of the array:
arr.forEach((value, index) => console.log(value, index));

JavaScript forEach loops can also be used to iterate objects by using Object.keys(), passing it the object you want to iterate over, which returns an array of the object’s own properties:
Object.keys(obj).forEach((key) => console.log(obj[key]));

Alternatively, you can forEach to loop over the values of properties directly if you don’t need access to the properties using Object.values():
Object.values(obj).forEach((value) => console.log(value));

Note that Object.values() returns the items in the same order as for…in.
Conclusion
By using the JavaScript for…in loop, we can loop through keys or properties of an object. It can be useful when iterating object properties or for debugging, but should be avoided when iterating arrays or making changes to the object. I hope you’ve found the above examples and explanations useful.
If you’d like to learn more about for…in loops, including their browser support and usage examples, check out the Mozilla docs.

Coded at

Share your love

One comment

%d bloggers like this: