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
  • This is the array on which the .forEach() function was called.

  • index
  • This is the index of the current element being processed by the function.

  • element
  • 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

1,841,2209


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.