Iterating through Arrays with forEach

One method to iterate through an array in JavaScript is forEach(). This method goes through each element of the array one at a time and can be useful when applying operations to specific elements within the array.

Call a function on each element in an array

This example uses the forEach() method to call a function on each element in the fruits array; the function causes each item to be logged to the console, along with the item's index number.

const fruits = ["Apple", "Mango", "Cherry"];
fruits.forEach((item, index, array) => {
  console.log(item, index);
});
// Apple 0
// Mango 1
// Cherry 2



Source: Mozilla, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#call_a_function_on_each_element_in_an_array
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

Last modified: Thursday, July 6, 2023, 8:54 PM