Open In App

What is forEach() method in JavaScript ?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The forEach() method in JavaScript is used to iterate over the elements of an array and execute a provided callback function once for each element. It provides a convenient way to perform operations on each element of an array without the need for a traditional for loop.

Syntax:

array.forEach(callback(element, index, arr), thisValue);

Parameters:

  • callback: This parameter holds the function to be called for each element of the array.
  • element: The parameter holds the value of the elements being processed currently.
  • index: This parameter is optional, it holds the index of the current value element in the array starting from 0.
  • array: This parameter is optional, it holds the complete array on which Array.every is called.
  • thisArg: This parameter is optional, it holds the context to be passed as this is to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.

Example: In this example, the Array.forEach() method is used to copy every element from one array to another.

Javascript




// JavaScript to illustrate forEach() method
function func() {
 
// Original array
const items = [12, 24, 36];
const copy = [];
items.forEach(function (item) {
    copy.push(item + item + 2);
});
console.log(copy);
}
func();


Output

[ 26, 50, 74 ]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads