tags:

views:

46

answers:

1

I've read plenty of reasons not to use for-in in Javascript, such as for iterating through arrays.

http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays

So in what use cases is it considered ideal to use for-in in JS?

+3  A: 

You can safely use for-in loops to enumerate over the properties of an object:

var some_obj = {
  name: 'Bob',
  surname: 'Smith',
  age: 24,
  country: 'US'
};

var prop;

for (prop in some_obj) {
  if (some_obj.hasOwnProperty(prop)) {
    console.log(prop + ': ' + some_obj[prop]);
  }
}

/* 
Output:
  name: Bob
  surname: Smith
  age: 24
  country: US
*/

It may be important to use the hasOwnProperty() method to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

Daniel Vassallo
ah right, properties in an object. makes sense, thanks!
chimerical