The foreach loop goes through all the elements in the array and gives them to you one by one, without having to iterate over the iteration variable using "i". For example, you can do this:
var result = 0; process.argv.forEach(function(element){ result = result + element; });
There is a difference between your code and this code: your code skipped the first two elements because "i" started with 2. This is harder to do in the foreach loop, and if you need to, you must stick to the loop.
The foreach loop sets counters for you. Comfortable but less flexible. It always starts with the first element and ends with the last. One great thing to notice is that we also donβt need to do anything like β[i]β. The array element is pulled and passed to our function.
In conclusion, the foreach loop is simply simplified for the loop for cases where you need to look at each element of the array.
I personally find that the foreach loop in node.js is ugly, as it is not an operator, but just a function related to arrays. I prefer how they look like php, where they are part of the language:
$result = 0; foreach ($process as $element) { $result = $result + $element; }
But this is just a personal taste.
Damien black
source share