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:
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.
My questions are:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With