for-in JavaScript Loop | How to use for-in Loop?

Using loops such as for-in JavaScript loop, you can reduce a huge amount of repetitive tasks and automate things so easily.

In this JavaScript Guide, you will learn a detailed explaination of JavaScript for-in statement with a couple of beginner friendly examples.

So, Let’s start learning point by point-

 

What is for…in loop in JavaScript

In simple words, you can think of for…in loop as a coding version of a Game, where you are ordering someone to take N steps in one direction, then M steps in another until it reaches destination.

For example, the logic behind “Going three steps towards the East” could be expressed this way with a regular for-Loop:

for (let step = 0; step < 3; step++) {

    // The 'step' runs 3 times, with values from step 0 to 2...
	
    console.log('Walking Towards East Direction...');

}

 

Using for…in Loop:

Unlike for loop, The forin loop works with a different set of parameters. It iterates over the properties of any JavaScript object, or the elements of an array.

Generic Syntax:

for( variable in object ) {

    // Some Code to be executed...

}

 

Example 1: Using Object’s Properties

Let’s have a look, how forin loop access all the values of an object using its properties-

// An object with some properties 
var student = { "name": "David", "surname": "Mullar", "rno": "101" };
 

// Loop through all the properties in the object
for( var eachProperty in student ) {  
      document.write("<div>" + eachProperty + " = " + student[ eachProperty ] + "</div>"); 
}

Here, the variable eachProperty with fetch and hold value of every single property of object student.

 

Example 2: Using Array

The forin loop can also work with a JavaScript array.

// An array 'JSbooks' with some elements
var JSbooks = ["JsForBeginners", "JsForMidLevel", "JsForExperts", "JsForAll", "JsByShubhamKLogic"];
 
// Loop through all the elements in the array 
for(var eachBook in JSbooks) {
    document.write("<div>" + JSbooks[eachBook] + "</div>");
}

 

 

Interview Tip***
Avoid using for-in loop to iterate over an array where the index order is important. It would be a lot better to use a regular for loop with a numeric index. For reason, Check out the below code snippet output-

Avoid using for_in JavaScript loop in case of Arrays.

 

Final Example: With HTML

<!DOCTYPE html>
<html>                                              <!-- Step 1: Create an HTML Web Document -->
    <body>
        <p id="demoParaId"></p>    <!-- Step 2: Create a paragraph to display information --> 

        <script>                                    /*   Step 3: Embed JavaScript   */

            var website = { firstName: "ShubhamKLogic.com", 
                         lastName: "<br>A Computer Science and Programming Portal for All - ", 
                         rank: 33 
            };

            var websiteDetails = "";
            var attributes;

            for (attributes in website) {                            /* for...in Loop will process all the properties of object 'website' */
                websiteDetails += website[attributes];
            }
            document.getElementById("demoParaId").innerHTML = websiteDetails;

        </script>
    </body>
</html>

 

In the above example, we have used JavaScript for_in loop with an HTML5 paragraph element to display the website information using this special loop.

Output:

Once you will save the above code in as DemoForInLoopExample.html file and open it using a web browser as chrome, you will see that the information is successfully printed on a webpage as following-

ShubhamKLogic.com
A Computer Science and Programming Portal for All - 33

 

Wrap Up 

Now, we know that the purpose of the for-in statement is to enumerate over the properties of objects. So far, we have learned, What is for-in loop in JavaScript?, cleared all the doubts such as- Can I use for-in loop in JavaScript?

I hope you’ve learned how to use for-in loop. Check other related useful JS articles that you may like–

Leave a Comment