JavaScript in 60 Seconds

Foreach loop

What is a forEach loop?

A loop allows you to repeat an action based on some condition, similar to an if statement. In the prior lesson you met the for loop. The foreach loop is similar…

The big difference is that 1. it loops over a list of items and 2. it runs a function on that item.

var sum = 0; [10, 30, 100, 4, 2].forEach(function(item){ // item will be 10, then next cycle 30, next cycle 100 etc... sum = sum + item; }); console.log('sum', sum);