forEach()

The forEach method in JavaScript arrays is utilized to execute a designated function for each element within the array a single time.

Syntax

The syntax for the forEach method is illustrated as follows:

Example

array.forEach(callback(currentvalue,index,arr),thisArg)

Parameter

callback - It denotes the function responsible for evaluating the condition.

currentvalue - The current element of array.

index - This parameter is not mandatory. It represents the index of the current element.

arr - This parameter is not mandatory. It refers to the array that the forEach method is applied to.

thisArg - This parameter is not mandatory. It represents the value that will be utilized as the context of 'this' when the callback function is executed.

Return

undefined

JavaScript Array forEach method example

Let's see some examples of forEach method.

Example 1

In this section, we will utilize the forEach method to display the elements of the array.

Example

<script>

var arr = ["C", "C++", "Python"];



arr.forEach(function(fetch) {

  document.writeln(fetch);

});

</script>

Output:

Output

C C++ Python

Example 2

In this section, we will generate the Fibonacci series utilizing the forEach method.

Example

<script>

var sum = 0;

var arr = [10,18,12,20];



arr.forEach(function myFunction(element) {

    sum= sum+element;

  document.writeln(sum);

});

</script>

Output:

Output

10 28 40 60

Input Required

This code uses input(). Please provide values below: