How To Execute Foreach Loop In JavaScript?


The forEach method in Javascript iterates over the elements of an array and calls the provided function for each element in order.

The arr.forEach() method call the provided function for each element of the array. The provided function may perform any kind of operation on the elements of the given array.

Syntax
array.forEach(callback(element, index, arr), thisValue)
Description

Parameters: This method accepts Four parameters as mentioned above and described below:

  • array: the array on which the specified function is called.
  • forEach: the method called for the array with the required parameters.
  • function(element, index, arr): the function with its parameters which is required to run for each element of the array.
    • element: the value of the current element.
    • index: the index of the current element being processed.
    • arr: the array object on which function was called.
  • thisValue: value to be used as the function’s this value when executing it. “undefined” is passed if this value is not provided.

Example
<script> 
    // JavaScript to illustrate forEach() method 
    function func() { 
      
        // Original array 
        const items = [12, 24, 36]; 
        const copy = []; 
  
        items.forEach(function (item) { 
            copy.push(item-2); 
        }); 
  
        document.write(copy); 
    } 
    func(); 
</script>

Output:

10,22,34

I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close