JavaScript | Array forEach()
arr.forEach() function 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. The syntax of the function is as follows:
arr.forEach(function callback(currentValue[, index[, array]]) { }[, thisArg]);
Arguments The argument to this function is another function that defines the condition to be checked for each element of the array. This function itself takes three arguments:
- array
- index
- element
This is the array on which the .forEach() function was called.
This is the index of the current element being processed by the function.
This is the current element being processed by the function.
Another argument thisValue is used to tell the function to use this value when executing argument function.
Return value The return value of this function is always undefined. This function may or may not change the original array provided as it depends upon the functionality of the argument function.
Example for the above function is provided below:
Example 1:
const items = [1, 29, 47]; const copy = []; items.forEach(function(item){ copy.push(item*item); }); print(copy);
Output:
1,841,2209
In this example the function forEach() calculates the square of every element of the array.
Code for the above function is provided below:
Program 1:
<script> // JavaScript to illustrate substr() function function func() { // Original array const items = [1, 29, 47]; const copy = []; items.forEach( function (item){ copy.push(item*item); }); document.write(copy); } func(); </script> |
Output:
1,841,2209
Recommended Posts:
- JavaScript | typedArray.forEach() with Examples
- ES6 | Array forEach() Method
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
- How to get the elements of one array which are not present in another array using JavaScript?
- How to check whether an array is subset of another array using JavaScript ?
- Node | URLSearchParams.forEach()
- RMS Value Of Array in JavaScript
- JavaScript | Array pop()
- JavaScript | Array unshift()
- JavaScript | Array.from() method
- JavaScript | Array map() Method
- JavaScript | Array indexOf()
- JavaScript | Array shift()
- How to Convert Array to Set in JavaScript?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.