JavaScript For/In Loop

in STEMGeekslast year


There is another kind of loop that JavaScript has provided since the very beginning and it is known as for/in or simply 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">
<title>For/in Loop</title>
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]);

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


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".

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

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


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