1

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

Why is using "for...in" with array iteration a bad idea?

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

Community
  • 1
  • 1
chimerical
  • 5,883
  • 8
  • 31
  • 37

1 Answers1

3

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
  • 337,827
  • 72
  • 505
  • 443