Array Methods

Methods for Iteration

🙋 Need help? Ask an expert now!

If the use of for loops or the for-of and for-in loops still confuse you, don't worry, the forEach() method also help us iterate through an array. The forEach() methods loops through the elements one by one and executes the statements inside the method block until all the elements have been passed. The syntax and function of the forEach() method is shown below.

arrayname.forEach(function)

  • runs the function for each element of the array
  • iterates the elements and passes each element as argument to the function

The function is directly inside the forEach() method as shown above. The function will run for each element, thus printing the index of each value in the array as well as the value itself. The forEach() method might not be the ideal method to loop through an array right now, but as you learn more about functions, it might be the method you end up using due to the simple and concise syntax.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 1, 2, 3, 5, 8, 11];
            let sum = 20;
            arr.forEach(function(item, index) {
              sum += item;
            });
            console.log(sum);
            

What will the following code segment print to the console?