Object manipulation statements | for-in

The for-in loop allows you to cycle through the properties of an object to display or manipulate their values.


for (var variable_name in object_name) {
JavaScript statements go here
}

For example, if you want to cycle through the properties of an instance of MyCustomizedComputer object in order to display the values on the screen then using for-in loop is a time saver since you don’t have to type each property name.


//This is the object
function MyCustomizedComputer (CPU, RAM, SSD) {
	this.CPU = CPU;
	this.RAM = RAM;
	this.SSD = SSD;
}

//This is the new instance
var DanComputer = new MyCustomizedComputer ("i5", "8GB", "120GB");

//This is for-in loop
for (var DisplayProperties in DanComputer) {
	document.write (DanComputer [DisplayProperties] );
	}

Notice DanComputer[DisplayProperties] which is unfamiliar. It is an array to store the values of the properties.

Leave a Reply