Javascript for in loop
Notes:
JavaScript for in loop:
To traverse (or loop through) attributes of an object, we use for in loop
Objects represent real world entities.
Ex: Car, Student, College, Employee, Company, Atom, World, etc.
These real world entities can be represented in the software world using objects.
Ex:
var Car = { model: "maruti", number: "m007", color: "red" };
var Student = {rollNum:51, name:”Manjunath”, marks:85};
Objects contain collection of key (attribute) & value (attribute value) pairs.
Syntax:
for(var variableName in ObjectName)
{
statement(s);
}
Ex:
var Car = { model: "maruti", number: "m007", color: "red"}; // literal notation
for(var attribute in Car)
{
document.write(attribute, " : ",Car[attribute],"<br/>");
}
output:
model : maruti
number : m007
color : red
Ex:
var Student = { rollNum: 51, name: "Manjunath", marks: 98}; // literal notation
for(var attribute in Student)
{
document.write(Student[attribute],"<br/>");
}
Note:
It is kind of forward for loop
Limitation of for in loop is you will not be having any control over the iteration.
Interview Questions: