Tutorialspoint.dev

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:

<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


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter