Menu
Coddy logo textTech

For Each

Lesson 10 of 18 in Coddy's Array Methods in JavaScript course.

The forEach() method is a built-in function for arrays that executes a provided function once for each element in the array. This function, called a callback function, can perform various operations on the elements, such as logging, modifying, or collecting information. The order of execution is from the first element (index 0) to the last.

Let's create an array of fruits and use forEach() to log their names and prices:

const fruits = ["apple", "banana", "orange"];
const prices = [1.50, 0.75, 2.00];

fruits.forEach((fruit, index) => {
  console.log(`${fruit} - ${prices[index]}`);
}); 

/* Output:  apple - $1.5
            banana - $0.75
            orange - $2  
*/

Callback Function: This function takes three arguments:

  • element: The current element being processed.
  • index: The index of the current element in the array.
  • array: The original array that forEach() was called on (optional).
challenge icon

Challenge

Easy

We have a group of four children holding 3, 4, 7, and 2 chocolates, respectively, as given in the chocolates array.

Your task is to write JavaScript code to double the amount of chocolates for each child and log the array.

Try it yourself

let chocolates = [3, 4, 7, 2];

// Write code here

All lessons in Array Methods in JavaScript