JavaScript For/In Loop

avatar


image.png

There is another kind of loop that JavaScript has provided since the very beginning and it is known as for/in or simply for..in loop. While for/of loop that we discussed previously is used for iterable objects like array, string and so on, the for/in loop is used for iterating over the JavaScript objects. The basic syntax is:

for (let/var/const property_name in object_name)
{
 //Body of Loop.
}

Lets see a simple example where we will create a simple object and then iterate over this object to print each value along with their property name.

<!DOCTYPE html>
<html lang="en">
<head>
<title>For/in Loop</title>
<script>
var Bike1 = {
        Brand: "Apache",
        Model: "RTR 200",
        Price: 350000,
        Mileage: "40 km/l",
        Speed: "127 km/hr",
    }

    for (var kname in Bike1){
        console.log(kname + ":" + Bike1[kname]);
    }
</script>
</head>
<body>
</body>
</html>

Now, if you open your console and see the output in the browser, you can see the following:

image.png

The for/in loop also works with the object that inherits from another object. We can create another object called Bike2 in above code from the prototype of Bike1 object and then add new properties called "Total_Gear".

<script>
    var Bike2 = Object.create(Bike1);
    Bike2.Total_Gear = 5;

    for (var kname in Bike2){
        console.log(kname + ":" + Bike2[kname]);
    }

</script>

Now if we loop through its properties and print it along with their value you will get the following output in your console.

image.png



0
0
0.000
0 comments