The JavaScript “for in” statement allows you to literally “loop” through all the properties of an object, without knowing ahead of time what the object will be or how many properties it will have

Seems as though one of the most over-looked and under-used tools in the JavaScript language is the “for in” statement. This statement allows you to essentially say: “Hey, if I have an object, any object, I wanna know what the name and value of every one of it’s properties is.”

No problem dude.

The “for in” statement creates a loop, much like the typical “for ( i=0, i <+ ###, i++)”, but  you can think of it as more of: “for (x = the first property in an object, go until x == the last property in the object, go to the next property in the object”). Needing to know all the names and values of a given object at run time is a scenario that comes up more than you may think, and being able to satisfy that need is a huge (huge) asset.

Example # 1

So, in Example # 1, we created a JavaScript object literal and assigned it to the variable “car”. This object has four properties. We then use a JavaScript “for in” loop to literally loop through the properties of this object. note that in order to build our dynamic statement, we first reference “prop”, which is the variable that represents the name of the currently examined property (i.e. “maker”). In order to the actual value of prop, we use bracket syntax, as opposed to dot notation or dot syntax. This is because in order to use dot notation, we would have to actually know the name of the property (i.e. “car.maker”). Since we only have a variable to use, we can say “car[prop]”, because bracket notation allows us to use a variable, or any valid JavaScript expression inside the bracket.

The output of example # 1 would be:

The maker of this car is: honda
The color of this car is: blue
The type of this car is: sedan
The mpg of this car is: 32

Summary

So, as you can see, the JavaScript “for…in” statement is easy to use and incredibly useful. It helps to write code that deals with objects that are unknown at run time, but as a result, can be easily enumerated and acted upon.

Helpful links for the JavaScript “for in” statement

http://store.kevinchisholm.com/javascript-training/javascript-object-inspection-using-the-for-in-statement/

http://www.w3schools.com/js/js_loop_for_in.asp

http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

http://webreflection.blogspot.com/2009/10/javascript-for-in-madness.html

One Comment

Comments are closed.