forEach Functions

The for loop uses a verbose syntax. Here's a for loop that iterates through an array of strings:

var people = ["manuel", "sid", "li li"];
for (var i = 0; i < people.length; i++) {
  console.log(people[i] + " is a person");
}

The forEach() function can do the same thing but with cleaner syntax. Here is how we would iterate through the same people array using forEach():

var people = ["manuel", "sid", "li li"];
people.forEach(function(person) {
  console.log(person + " is a person");
});

The forEach() function takes an anonymous function as an argument; this type of anonymous function is commonly referred to as a callback. The forEach() function iterates through all the people in the array and passes each person as an argument to the callback function.

Let's assign the callback function to a variable to make the code clearer.

var peopleSpeaker = function(person) {
  console.log(person + " is a person");
}
people.forEach(peopleSpeaker);

The forEach() function calls the peopleSpeaker() function three times.

peopleSpeaker("manuel");
peopleSpeaker("sid");
peopleSpeaker("li li");

Traditional JavaScript for loops are ugly and hard to read. Use the forEach() function to make your code more readable.

Question Click to View Answer

What does the following code print to the console?

var numbers = [11, 22, 33];
var result = 0;
numbers.forEach(function(number){
  result += number;
})
console.log(result);

66

The forEach() function is used to iterate over all the numbers in the array and add them to the result.

What does the following code print to the console?

var sacredTetrad = [1, 2, 3, 4];
var result = [];
sacredTetrad.forEach(function(number) {
  result.push(number * number);
})
console.log(result);
[1, 4, 9, 16]

The forEach() function is used to iterate over the sacredTetrad array and append the square of every number to the result array.

What does the following code print to the console?

var fun = ["dance", "party"];
var bang = function (x) {
  console.log(x + "!");
}
fun.forEach(bang);
dance!
party!

The forEach() function iterates over every element in the fun array and calls the anonymous function that is assigned to the bang variable. The following code yields an equivalent result:

bang("dance");
bang("party");
<-- Previous (Loops With If) Next (Map Function) -->