« JavaScript 1.6 - Array and String generics | Main | Further Reading »

Sun, Oct 09, 2005

for..in vs. for each

JavaScript features for..in loops (enumerations) for a long time now. You can use it to easily enumerate all property names of an object. E4X (ECMAScript for XML, ECMA-357) specifies "for each" loops that enumerate the property values instead. So, where's the difference?

Consider the object

var obj = { lastName: "Much", firstName: "Thomas" };

The for..in loop

for (var i in obj) document.writeln(i + "<br>");

would yield

lastName
firstName

whereas the for each loop

for each (var i in obj) document.writeln(i + "<br>");

would display

Much
Thomas

To achieve the latter with a for..in loop, you'd have to write

for (var i in obj) document.writeln(obj[i] + "<br>");

Posted by Thomas Much at 22:09
Categories: JavaScript