The for…in loop in JavaScript loops over all of the properties in an object. This article will explain why and how to use it.
JavaScript Objects
JavaScript objects are a kind of variable which store the properties for an item you are representing in your code. For example, you may have a car object, which of which the make, year, model, and colour of a car are it’s properties. Each car object would have it’s own separate list of properties which define that car.
JavaScript objects can also be used as hash tables – providing similar functionality.
Why Loop Over Object Properties?
Being able to loop over the properties stored in an object is useful – you may simply want to inspect the contents of an object, or you may wish to update certain values in the object. For example, you may wish to take all of the properties of an object and join them into a single string so that the object can be represented as text only.
for…in Loop JavaScript Syntax
The for… in statement has the following syntax:
for (VARIABLE in OBJECT) { STATEMENTS }
Note that:
- OBJECT is the object of which the properties will be looped over
- VARIABLE is the name of the variable which will be used to access each property of OBJECT as they are iterated over
- This value will be the name of the property – not the value!
- STATEMENTS are the statements that will be executed for each iteration (or loop)
for…in Code Examples
var myCar = { make: 'Ford', model: 'Pinto', colour: 'Red', year: '1982' } var carString = ''; for (prop in myCar){ carString += prop + ': ' + myCar[prop] + ','; } console.log(carString);
Above, the variable myCar is defined containing an object with some information about a car. An empty string variable is then defined carString which will have information about the car added to it.
The for…in loop iterates over each property in the myCar object. prop is the name given to the variable which will contain the name of each property of myCar as it is looped over.
In each iteration, carString is appended to using the += operator. The appended value is the name of the property, followed by the value of the property accessed by using myCar[prop] – remember, prop is always a string containing the name of the property currently being looped over.