forEach Loop

forEach Loop

  • forEach() is an Array method executes a provided function once for each item (or element) in the array

  • The function used in forEach is called a callback function because it is being passed as a parameter into another function (we’ll cover these concepts in more detail in a later class)

  • The callback function for forEach provides the following:

    • element - this current element from the array that is being evaluated

    • index - this represents the current element’s index (or position in the array)

callbacks are used extensively in JavaScript; we will discuss them more in detail when we do a deeper dive into functions later in the course

someArray.forEach(function(element, index) {
  // code block to be executed for each element in the array
})

Example

const chipmunks = ["alvin", "simon", "theodore"]

chipmunks.forEach(function(element, index) {
  console.log(`${element} is at index ${index}`)
})

JS Bin on jsbin.com

Exercise

Write a program that uses a forEach loop to print each of the fruit names (found in the provided fruits array) in all caps

JS Bin on jsbin.com