foreach vs for js code example
Example 1: foreach in javascript
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
Example 2: for loop vs for each loop
1-
For Loop:
-It is flexible to iterate array
both ascending and descending order.
For Each:
-It iterates from initial to end
2-
For Loop:
-It runs until given condition become false
For Each:
-Keeps execution until last element
get executed
3-
For Loop:
-It use index
For Each:
-It use iteration
4-
For Loop:
-Accepts both object collections and non object collections
For Each:
-Accepts only object collections
Example 3: for vs foreach loop
1-
For Loop:
-It is flexible to iterate array
both ascending and descending order.
For Each:
-It iterates from initial to end
2-
For Loop:
-It runs until given condition become false
For Each:
-Keeps execution until last element
get executed
3-
For Loop:
-It use index
For Each:
-It use iteration
4-
For Loop:
-Accepts both object collections and non object collections
For Each:
-Accepts only object collections