The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array.
array.forEach(callback(element, index, arr), thisValue)
Parameters: This method accepts five parameters as mentioned above and described below:
- 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.
Return value: The return value of this method is always undefined. This method may or may not change the original array provided as it depends upon the functionality of the argument function.
Below are examples of the Array forEach() method.
Example 1: In this example, the Array.forEach() method is used to copy every element from one array to another.
const items = [12, 24, 36];
const copy = ;
copy.push(item + item+2);
Example 2: In this example, the method forEach() calculates the square of every element of the array.
const items = [1, 29, 47];
const copy = ;
copy.push(item * item);
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1.5 and above
- Internet Explorer 9 and above
- Opera 9.5 and above
- Safari 3 and above
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!