Type Here to Get Search Results !

JavaScript For vs forEach


forEach 


var people = ["Bob", "Jane", "Mary", "Chris"];

for(var person in people) {
  processPerson( person );
}

This is a very common pattern and ES5 introduces a new Array function, Array.prototype.forEach to make this really easy:

Using forEach makes this code a little shorter, but there are other more important reasons why it is often a better choice. 

  1. You don’t have to write the array iteration logic yourself, which means fewer opportunities for bugs, and in this case less chance of an accidental off-by-one error or incorrect length calculation. 
  2. forEach handles arrays with empty elements automatically, skipping those indexes that don’t have values. 
  3. Putting the body of the loop into a function ensures that any variables defined will only be in scope within the loop body, reducing the risk of loop variables conflicting with other variables in your code.


for



for(var i = 0; i < people.length; i++) {
  processPerson(people[i]);
}

If so, you’ve probably noticed that for..in loops give you the indexes of the elements in the array, not the elements themselves. 
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

bogger post ad 1

Below Post Ad

bogger post ad 2

ezoic

Ads Section