For Loop in JavaScript: How to Use the for…in Loop

Loops allow us to cycle through objects in arrays or objects and print them, modify them, or perform other types of actions or actions. There are different types of loops, and for loops in JavaScript allow us to iterate through a collection (such as an array).

In this article, we will learn about for Loop provides JavaScript. we will see how for...in Loop statement is used in JavaScript, syntax, how it works, when to use or avoid it, and what other type of loop we can use instead.

Why Use Loops in Javascript Code

In JavaScript, as in other programming languages, we use loops to read or access the objects of a collection. The collection can be an array or an object. Each time the loop statement cycles through the items in a collection, we call it an . They say Travel,

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

Definition of for … in loop

Javascript for The loop goes through the keys of a collection or iterates over them. Using these keys, you can access the item that represents in the collection.

A collection of objects can be either arrays, objects or even strings.

Syntax of for in loop

for The loop has the following syntax or structure:

for (let key in value) 
  

In this code block, value is a collection of objects we are iterating over. It can be an object, array, string, etc. key will have the key of each item in valueChanging to the next key in the list on each iteration.

Note that we use let either const To declare key,

using for loop with objects

when using for...in Loop, iterable keys or properties to iterate over an object in JavaScript – represented by, in the snippet above, key Variable – The object has its own properties.

Since objects can obtain items through the prototype chain, which contains the default methods and properties of objects as well as object prototypes that we can define, then we must use is your property,

For example loop over an iterable object

In the following example, we are 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] )






Note that the order of repetition for keys is ascending (that is, starting with digits in numerical order and then alphabetically). However, this output order is different from the index order of the items created when the object is initialized.

see pen
looping objects
by Sitepoint (@ sitepoint) Feather codepen,

Using for… in a loop with Arrays

while using for...in loop to iterate arrays in javascript, key In this case the elements will have indices. However, the indices can be iterated in a random order.

So if value variable in for...in The loop syntax structure we showed above was an array of five objects, key Wouldn’t be guaranteed to be 0 to 4. Some indices may precede others. Details of when this can happen are explained later in this article.

In the for…loop array example

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

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

for (let key in arr) 
  console.log(key + ": " + arr[key])






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

see pen
looping array
by Sitepoint (@ sitepoint) Feather codepen,

Using a for… in a loop with strings

you can loop over a string with javascript for...in the noose. However, doing this is not recommended, as you will be looping over the indices of the characters instead of the characters themselves.

A for… in the loop string example

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

const str = "Hello!";

for (let key in str) 
  console.log(key + ": " + str.charAt(key));








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

see pen
strings loop
by Sitepoint (@ sitepoint) Feather codepen,

Let’s look at the situations that JavaScript for...in Best suited for loops.

Iterating Objects with Javascript… in a Loop

Because for...in The loop only iterates over the enumerable properties of an object – which are the properties of the object itself, rather than the properties: toString that are part of the object’s prototype — it’s good to use a for...in Loop to iterate objects. a for...in Loops provide an easy way to iterate over an object’s properties and eventually its values.

debugging with a … in loop

Another good use case for Javascript for...in Loop debugging. For example, you might want to print an object’s properties and its values ​​to the console or to an HTML element. in this matter, for...in The loop is a good option.

while using for...in For debugging loops on objects and their values, you should always keep in mind that the iterators are not ordered, which means that the order of objects that the loop iterates over can be random. Therefore, the order of accessed properties may not be as expected.

When not to use JavaScript for… in a loop?

Now let’s look at the situations where a for...in The loop is not the best option.

sort iteration of arrays

Since index order is not guaranteed in iterators, when it is used for...in Loop, it is recommended not to iterate arrays if it is necessary to maintain order.

This is especially necessary if you want to support browsers such as IE, which iterate in the order the items are created, rather than in the sequential order. This is different from the way current modern browsers work, which iterates arrays based on indices in ascending order.

So, for example, if you have an array of four items and you insert an item in position three in a modern browser for...in The loop will still iterate the array in order from 0 to 4. In IE, a . while using for...in loop, it will iterate the four items that were originally in the array at the beginning and then access the item that was added at position three.

change while iterating

Any addition, deletion or modification of properties does not guarantee ordered iteration. change properties a for...in The loop should be avoided. This is mostly due to its uncontrolled nature.

Therefore, if you remove an item before it is reached in the iteration, the item will not be seen at all throughout the loop.

Similarly, if you make changes to a property, it doesn’t guarantee that the item won’t be revisited. So, if a property is changed it can be seen in the loop twice instead of once.

Furthermore, if a property is added during an iteration, it may or may not happen during the iteration.

Because of these conditions, it is best to avoid making any changes, deletions, or additions to an object. for...in the noose.

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

see pen
add object loop
by Sitepoint (@ sitepoint) Feather codepen,

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

Alternatives to For Loops in Javascript

So in situations where a for...in loop is not the best option, what should you use instead? let’s take a look.

using for loop with arrays

a. it’s never wrong to use for the noose! Javascript for Loop is one of the most basic tools for looping over array elements. for The loop allows you to take full control of the indices when you iterate an array.

This means that when using for Loop, you can go back and forth, change items in the array, add items, and more, all 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]);

for each method for arrays and objects

For each Javascript has a method on the array prototype that allows us to iterate over the elements of an array and their indices in a callback function.

callback function There 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, this means that a callback function will be executed for each iteration that receives the current item in the iteration as a parameter.

For example, the following statement iterates over the variable arr and prints its values ​​in console 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 Loop can also be used to iterate objects Object.key()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 to use properties object.value(),

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

note that Object.values() Returns items in the same order as for...in,

conclusion

by using javascript for...in Loop, we can loop through the keys or properties of an object. This can be useful when iterating object properties or for debugging, but should be avoided when iterating arrays or making changes to objects. I hope you find the above examples and explanations useful.

Leave a Reply