JavaScript alternative to "for each" loop

33,296

Solution 1

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.

Solution 2

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]);
}

Solution 3

You can make use of the new ECMAScript 5th Edition functions:

Object.keys(obj).forEach(function (key) {
    console.log(key, obj[key]);
});
Share:
33,296
user1537366
Author by

user1537366

Updated on July 09, 2022

Comments

  • user1537366
    user1537366 almost 2 years

    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?

  • user1537366
    user1537366 over 11 years
    Yes, 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?
  • Quentin
    Quentin over 10 years
    @Benedictus — No. It's in JavaScript 1.0. Netscape 2 supports it!
  • pherris
    pherris almost 8 years
    ^ this is how I solved the no-restricted-syntax error from eslint when the forinstatement is used.