Javascript for…in Loop Example
In this article, we will see how to use javascript for…in the loop with example. This loop statement is used to traverse (or loop through) attributes of an object. Objects represent real-world entities like cars, students, colleges, companies, etc.
These real-world entities can be represented in the software world using objects.
Ex:
var Car = {model : "suzuki", number : "m008", color : "silver" };
var Student = {rollNum : 45, name : "john", marks : 87};
Objects contain a collection of key (attribute) and value (attribute value) pairs.
Syntax:
for(var variableName in ObjectName)
{
objectname[variableName];
}
Ex:
var Car = {model : "suzuki", number : "m008", color : "silver" };
for(var attribute in Car)
{
document.write(Car[attribute], "<br/>");
}
Output:
- In the above code, we have created an object variable car.
- If we want to display all the values of the Car object, then we need to use “for in loop“.
- Here first we put the “for” keyword inside parentheses we gave “var” as a datatype, “attribute” as a VarName, “in” as a keyword, and “Car” as objectName.
- Then inside the loop, we print the “Car[attribute]”.
- See the above code the values of the Car object are displayed successfully.
Note:
This loop is kind of forward for a loop.
The limitation of “for in loop” is you will not be having any control over the iteration.
I hope you have understood a little about for…in loop in this article. If you have any doubts about this then please comment below.