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?
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?
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.