JavaScript Tutorial


Total available pages count: 33
Subject - JavaScript Frameworks

For-in

For-in loop

A for-in loop iterates through the properties of an object and executes the loop's body once for each enumerable property of the object.

Example:

var student = { name:"Slightbook", age: 19, degree: "Bachelors" };
for (var item in student)
{
	alert(student[item]);     // => "Slightbook", then 19, then "Bachelors"
}

With each iteration, JavaScript assigns the name of the property (a string value) to the variable item. In the example above these are name, age, and degree.

With each iteration, JavaScript assigns the name of the property (a string value) to the variable item. In the example above these are name, age, and degree.

var Student = function(name)
{
	this.name = name;
}
Student.prototype.age = 26;
var student = new Student("Slightbook-2");
for (var item in student)
{
	if (student.hasOwnProperty(item))
	{
		alert (student[item]);         // => Slightbook-2. age is not displayed
	}
}

We have not discussed objects yet, but the student object has a name property on the object itself. Its prototype object has an age property. The for-in loop iterates overall properties, but the hasOwnProperty ensures that the age property on the prototype does not get displayed because it is not the student's own property.



Comments