Back to basics: for…in loops in JavaScript

Loops allow us to loop through items in arrays or objects and do things like print them, modify them, or perform other types of tasks or actions. There are different types of loops in JavaScript, and one of them is the for…in loop.

In this article, we will discover the for...in loop JavaScript provides. We will see 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 like in other programming languages, we use loops to read or access elements of a collection. The collection can be an array or an object. Each pass through the elements of a collection is called a iteration.

There are two ways to access an item in a collection. The first is to use its key in the collection, which is an index in an array or a property in an object. The second way is through the item itself, without needing the key.

Definition of the for…in loop

JavaScript for...in loop loops through or iterates over keys in a collection. Using these keys, you can then access the item it represents in the collection.

The collection of elements 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 block of code, value is the collection of elements we are iterating over. It can be an object, an array, a string, etc. key will be the key to each item in valuepassing on each iteration to the next key in the list.

Note that we use let Where const to announce key.

For loop iterating object properties with const 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.

Since objects can inherit things through the prototype chain, which includes default methods and properties of objects as well as object prototypes we might define, then we should use hasOwnProperty.

An example of a for…in loop object

In the following example, we loop over the following variable obj:

const obj = {
  1: "JavaScript",
  3: "PHP",
  2: "Python",
  4: "Java"
};

Inside the loop, we render the property and the value in a

element.

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

Note that the order of iteration is ascending for the keys (i.e. starting with numbers in numerical order then letters in alphabetical order). However, this output order is different from the index order of items created during object initialization.

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, indices can be iterated in random order.

So if the value variables in the for...in loop syntax structure we showed above was an array of five elements, key would not be guaranteed between 0 and 4. Some indices could precede others. Details on when this might happen are explained later in this article.

For…in loop array example

In the example below, we are looping over the following variable arr:

const arr = ["Javascript", "PHP", "Python", "Java"];

And inside the loop we return the index and 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 JavaScript for...in loop. However, it is not recommended to do so, as you will be looping over character indices rather than the characters themselves.

An example of a for…in loop string

In the example below, we are looping over the following variable str:

const str = "Hello, World!";

Inside the loop, we return the key, or index of each character, and the character at that index.

See the pen
String loop by SitePoint (@SitePoint)
on CodePen.

When to use a for…in loop

Let’s look at the situations that JavaScript for...in loop is best suited.

Iterating objects with a JavaScript for…in loop

Because the for...in loop iterates only the enumerable properties of an object – which are the object’s own properties rather than properties like toString that are part of the prototype of the object — it is good to use a for...in loop to iterate the objects. A for...in The loop provides a simple way to iterate over an object’s properties and, ultimately, its values.

Debugging with a for…in loop

Another good use case for JavaScript for...in the loop is being debugged. For example, you may want to print an object’s properties and values ​​to the console or an HTML element. In this case, the for...in buckle 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 unordered, which means that the order of the elements that the loop iterates over can be random. Thus, the order of properties accessed may not be as expected.

When not to use a JavaScript to…in the loop

Let us now examine the situations where a for...in loop is not the best option.

Ordered iteration of arrays

As the order of indexes in iterations is not guaranteed when using for...in loop, it is recommended not to iterate arrays if policing is needed.

This is especially critical if you’re looking to support browsers like IE, which iterate in the order in which elements are created rather than index order. This is different from how current modern browsers work, which iterate arrays based on indices in ascending order.

So, for example, if you have an array of four elements, and you insert an element at position three, in modern browsers the for...in loop will always iterate the array in order from 0 to 4. In IE, when using a for...in loop, it will iterate through the four elements that were originally in the array at the start, then reach the element that was added at position three.

Make changes during iteration

Adding, removing, or changing properties does not guarantee orderly iteration. Make changes to the properties of a for...in loop should be avoided. This is mainly due to its messy nature.

So if you delete an element before reaching it in the iteration, the element will not be visited at all in the whole loop.

Likewise, if you make changes to a property, this does not guarantee that the element will not be revisited again. So if a property is changed, it can be visited twice in the loop rather than just once.

Also, if a property is added during iteration, it may or may not be visited at all during iteration.

Because of these situations, it is best to avoid making changes, deletions, or additions to an object in a for...in loop.

Here is an example of adding an element in a for...in loop. We can see the result of the first loop and then of the second after making additions in the first loop.

See the pen
Added in Object Loop by SitePoint (@SitePoint)
on CodePen.

As you can see in the example above, the elements that have been added have not been iterated over.

Alternative Loop Types

Thus, in situations where a for...in loop is not the best option, what should you use instead? We’ll take a look.

Using a for loop with arrays

It never hurts to use a for loop! JavaScript for loop is one of the most basic tools for looping over array elements. the for loop lets you take full control of the indices when looping through an array.

This means that when using the for loop, you can move forward and backward, modify elements in the array, add elements, etc., while 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 that method or function’s execution. When it comes to forEach in JavaScript, this means that the callback function will be executed at 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 ​​to the console using forEach:

arr.forEach((value) => console.log(value));

You can also access the array index:

arr.forEach((value, index) => console.log(value, index));

JavaScript forEach loops can also be used to iterate over objects using Object.keys(), passing it the object you want to iterate over, which returns an array of the object’s properties:

Object.keys(obj).forEach((key) => console.log(obj[key]));

Alternatively, you can forEach To iterate through property values ​​directly if you don’t need to access properties using Object.values():

Object.values(obj).forEach((value) => console.log(value));

Note that Object.values() returns the elements in the same order as for...in.

Conclusion

Using JavaScript for...in loop, we can loop through keys or properties of an object. This can be useful when iterating over an object’s properties or for debugging, but should be avoided when iterating over arrays or modifying the object. I hope you found the above examples and explanations useful.

If you want to know more about for...in loops, including their browser support and usage examples, see the Mozilla documentation.

Comments are closed.