BloG

For Loop in JavaScript: Tips on how to Use the for…in Loop

Dec 5, 2022

Loops allow us to cycle through items in arrays or objects and do things like print them, modify them, or perform other forms of tasks or actions. There are different sorts of loops, and the for loop in JavaScript allows us to iterate through a group (reminiscent of an array).

In this text, we’ll learn concerning the for loop JavaScript provides. We’ll take a look at how for…in loop statements are utilized in JavaScript, the syntax, examples of how it really works, when to make use of or avoid it, and what other kinds of loops we are able to use as a substitute.

Why Use For Loops in JavaScript Code

In JavaScript, just as in other programming languages, we use loops to read or access the items of a group. The gathering will be an array or an object. Each time the loop statement cycles through the items in a group, we call it an iteration.

There are two ways to access an item in a group. The primary way is via its key in the gathering, which is an index in an array or a property in an object. The second way is via the item itself, with no need the important thing.

Definition of the for…in Loop

The JavaScript for loop goes through or iterates keys of a group. Using these keys, you possibly can then access the item it represents in the gathering.

The gathering of things will be either arrays, objects, and even strings.

Syntax of the for…in Loop

The for loop has the next syntax or structure:

for (let key in value) {

}

On this code block, value is the gathering of things we’re iterating over. It may possibly be an object, array, string, and so forth. key shall be the important thing of every item in value, changing on each iteration to the subsequent key within the list.

Note that we use let or const to declare key.

Using the for Loop with Objects

When using for…in loop to iterate an object in JavaScript, the iterated keys or properties — which, within the snippet above, are represented by the important thing variable — are the item’s own properties.

As objects might inherit items through the prototype chain, which incorporates the default methods and properties of Objects in addition to Object prototypes we would define, we should always then use hasOwnProperty.

For loop example over an iterable object

In the next example, we’re looping over the variable obj and logging each property and value:

const obj = {
“a”: “JavaScript”,
1: “PHP”,
“b”: “Python”,
2: “Java”
};

for (let key in obj) {
console.log(key + “: “ + obj[key] )
}

Notice that the order of the iteration is ascending for the keys (that’s, starting with digits in numerical order after which letters in alphabetical order). Nonetheless, this outputted order is different from the index order of the items as created when initializing the item.

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

Using a for…in Loop with Arrays

When using the for…in loop to iterate arrays in JavaScript, key on this case shall be the indices of the weather. Nonetheless, the indices is likely to be iterated in a random order.

So, if the worth variable within the for…in loop syntax structure we showed above was an array of 5 items, key wouldn’t be guaranteed to be 0 to 4. Some indices might precede others. Details on when this might occur is explained later in this text.

For…in loop array example

In the instance below, we’re looping over the next variable arr:

const arr = [“JavaScript”, “PHP”, “Python”, “Java”];

for (let key in arr) {
console.log(key + “: “ + arr[key])
}

And within the loop, we’re rendering the index and the worth of every array element.

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

Using a for…in Loop with Strings

You may loop over a string with the JavaScript for…in loop. Nonetheless, it’s not advisable to achieve this, as you’ll be looping over the indices of the characters fairly than the characters themselves.

A for…in loop string example

In the instance below, we’re looping over the next variable str:

const str = “Hello!”;

for (let key in str) {
console.log(key + “: “ + str.charAt(key));
}

Contained in the loop, we’re rendering the important thing, or index of every character, and the character at that index.

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

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

Iterating objects with a JavaScript for…in loop

Since the for…in loop only iterates the enumerable properties of an object — that are the item’s own properties fairly than properties like toString which might be a part of the item’s prototype — it’s good to make use of a for…in loop to iterate objects. A for…in loop provides a simple strategy to iterate over an object’s properties and ultimately its values.

Debugging with a for…in loop

One other good use case for the JavaScript for…in loop is debugging. For instance, it’s possible you’ll wish to print to the console or an HTML element the properties of an object and its values. On this case, the for…in loop is a superb alternative.

When using the for…in loop for debugging objects and their values, you must at all times take into accout that iterations aren’t orderly, meaning that the order of things that the loop iterates will be random. So, the order of the properties accessed may not be as expected.

When To not Use a JavaScript for…in Loop

Now let’s take a look at situations where a for…in loop isn’t one of the best option.

Orderly iterating of arrays

Because the index order within the iterations is just not guaranteed when using the for…in loop, it’s advisable to not iterate arrays if maintaining the order is mandatory.

This is particularly essential should you’re seeking to support browsers like IE, which iterates within the order the items are created fairly than within the order of the indices. That is different from the way in which current modern browsers work, which iterate arrays based on the indices in ascending order.

So, for instance, if you could have an array of 4 items and also you insert an item into position three, in modern browsers the for…in loop will still iterate the array so as from 0 to 4. In IE, when using a for…in loop, it’s going to iterate the 4 items that were originally within the array at first after which 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 needs to be avoided. This is usually as a result of its unordered nature.

So, should you delete an item before you reach it within the iteration, the item won’t be visited in any respect in your entire loop.

Similarly, should you make changes to a property, it doesn’t guarantee that the item won’t be revisited again. So, if a property is modified it is likely to be visited twice within the loop fairly than once.

As well as, if a property is added during iteration, it would or may not be visited through the iteration in any respect.

Resulting from 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 a component in a for…in loop. We are able to see the results of the primary loop then the second after making additions in the primary loop.

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

As you possibly can see within the above example, the weather that were added weren’t iterated over.

Alternatives to For Loops in JavaScript

So in those situations where a for…in loop isn’t one of the best option, what must you use as a substitute? Let’s have a look.

Using a for loop with arrays

It’s never flawed to make use of a for loop! The JavaScript for loop is some of the basic tools for looping over array elements. The for loop permits you to take full control of the indices as you iterate an array.

Because of this when using the for loop, you possibly can move forwards and backwards, change items within the array, add items, and more, while still maintaining the order of the array.

The next 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 technique on array prototypes that permits us to iterate over the weather of an array and their indices in a callback function.

Callback functions are functions that you simply pass to a different method or function to be executed as a part of the execution of that method or function. In relation to forEach in JavaScript, it signifies that the callback function shall be executed for every iteration receiving the present item within the iteration as a parameter.

For instance, the next statement iterates over the variable arr and prints its values within the console using forEach:

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

You can even access the index of the array:

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

JavaScript forEach loops will also be used to iterate objects through the use of Object.keys(), passing it the item you wish to iterate over, which returns an array of the item’s own properties:

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

Alternatively, you possibly can forEach to loop over the values of properties directly should 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 identical order as for…in.

Conclusion

Through the use of the JavaScript for…in loop, we are able to loop through keys or properties of an object. It may possibly be useful when iterating object properties or for debugging, but needs to be avoided when iterating arrays or making changes to the item. I hope you’ve found the above examples and explanations useful.