Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript alternative to "for each" loop

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?

like image 908
user1537366 Avatar asked Sep 28 '12 09:09

user1537366


People also ask

What can I use instead of for loop in JavaScript?

Use map() instead of for() loops Before I get started, this is going to teach you how the . map() function works. If you only have knowledge of for() loops in JavaScript, this article will require you to understand the Arrow Function Expression syntax (a.k.a. “fat arrow” functions).

What can I use instead of a for loop?

The most common way was to use for loop, iterate elements and find which is even. Instead of using for in this case, we can use the filter() method. This method also returns a new array.

What can we use instead of two for loops?

map() is an alternative to for loop when it comes to code organisation but doesn't do well when memory, speed is taken into account.

Does JavaScript have a for each loop?

The JavaScript forEach method is one of the several ways to loop through arrays. Each method has different features, and it is up to you, depending on what you're doing, to decide which one to use.


1 Answers

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]);
}
like image 117
Denys Séguret Avatar answered Sep 20 '22 01:09

Denys Séguret