Andy Hin Andy Hin - 6 months ago 18
Javascript Question

Iterating over array of objects javascript - odd behaviour?

var myArr = [{a:1, b:2}, {c:3, d:4}];

for (var item in myArr) {

Item returns the key (ex: 0, 1) instead of the object itself. Why?


Douglas Crockford recommends in JavaScript: The Good Parts to avoid using the for in statement.

If you use for in to loop over property names in an object, the results are not ordered.

The for in loop is best for iterating over name-value pairs, and the for each loop best for iterating over values i.e arrays.


var o = {'name':'Batman', 'age':33, 'city':'Gotham City'};
   for (var p in o) {
        console.log(p+': '+o[p]);

There’s no way we can get the property name if we were to use the For Each Loop for the above object.

Note :

  1. The For in Loop is best for name-value pairs.
  2. The For Each Loop is best for iterable values. Eg: arrays, and objects if you are not interested in the name of the property.