According to the MDN page at for each...in loop, this construct is deprecated. Is there an alternative that does exactly the same thing? The for...of loop does not iterate over non-integer (own enumerable) properties. If there isn't an alternative, why did they deprecate it then?
Asked
Active
Viewed 3.7k times
17
-
Good point [made here](http://stackoverflow.com/questions/242841/javascript-for-in-vs-for) – noel Sep 28 '12 at 09:34
3 Answers
17
To iterate over all the properties of an object obj
, you may do this :
for (var key in obj) {
console.log(key, obj[key]);
}
If you want to avoid inherited properties, you may do this :
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
console.log(key, obj[key]);
}

Denys Séguret
- 372,613
- 87
- 782
- 758
13
You can make use of the new ECMAScript 5th Edition functions:
Object.keys(obj).forEach(function (key) {
console.log(key, obj[key]);
});

Renaat De Muynck
- 3,267
- 1
- 22
- 18
-
5^ this is how I solved the `no-restricted-syntax` error from eslint when the `forinstatement` is used. – pherris May 16 '16 at 18:23
4
Is there an alternative that does exactly the same thing?
A for ... in
loop in which the first thing you do in the block of code is to copy foo[propertyname]
to a variable.

Quentin
- 914,110
- 126
- 1,211
- 1,335
-
1Yes, I guess there is only this work-around, which isn't really a language replacement for "for each". So they shouldn't have deprecated it, right? – user1537366 Nov 09 '12 at 15:02
-