Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between forEach and for loop in javascript

Tags:

I am wondering: Is there any significant difference between forEach and for loop in JavaScript.

Consider this example:

var myArray = [1,2,3,4];  myArray.forEach(function(value) {   console.log(value); });  for (var i = 0; i < myArray.length; i++) {   console.log(myArray[i]); } 

Here is part of my research:

  1. Performance: According to JsPerf : forEach is little slower than for loop.
  2. Usability: There is no way we can break/return from the callback in case of forEach loop.

For example: You want to find out if a number is prime or not. I think using for loop is much more easier than using forEach loop to do this.

  1. Readability: Using for loop makes code more readable than having forEach in code.
  2. Browser compatibility: forEach is Not supported in IE < 9 So that introduces some shim in our code.

My questions are:

  1. What are the advantages of forEach over for loop ?
  2. In what scenarios, forEach is more preferable.
  3. Why did even it come into JavaScript ? Why was it needed at all ?
like image 228
Sachin Avatar asked Sep 23 '14 12:09

Sachin


1 Answers

forEach is a method on the Array prototype. It iterates through each element of an array and passes it to a callback function.

So basically, forEach is a shorthand method for the use-case "pass each element of an array to a function". Here is a common example where I think Array.forEach is quite useful, compared to a for loop:

// shortcut for document.querySelectorAll function $$(expr, con) {     return Array.prototype.slice.call((con || document).querySelectorAll(expr)); }  // hide an element function hide(el) {     el.style.display = 'none'; }  // hide all divs via forEach $$('div').forEach(hide);   // hide all divs via for for (var divs = $$('div'), i = 0; i < divs.length; i++) {     hide(divs[i]) } 

As you can see, the readability of the forEach statement is improved compared to a for loop.

On the other hand, a for statement is more flexible: it does not necessarily involve an array. The performance of a normal for loop is slightly better, because there is no function call for each element involved. Despite of this, it is recommended to avoid for loops when it can be written as a forEach statement.

like image 146
9 revs Avatar answered Oct 05 '22 03:10

9 revs