For Each Loop
var colors = ['red', 'green', 'blue'];
for (var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
forEach with an Anonymous Function
var colors = ['red','green','blue'];
colors.forEach(function(color){
console.log(color);
});
var numbers = [1,2,3,4,5];
var sum = 0;
numbers.forEach(function(number){
sum += number;
});
console.log(numbers + ' totals ' + sum);
forEach with a Declared Function
var colors = ['red','green','blue'];
function myFunction(thing){
console.log(thing);
}
colors.forEach(myFunction); // we're passing a reference to a function
colors.forEach(myFunction(color)); would not work because myFunction(color) gets evaluated immediately before the forEach loop gets executed and it does not return a reference to a function. (It errors out because the color variable is undefined when myFunction gets evaluated.)



