Array Iteration in JavaScript

In JavaScript (Array iteration) array forEach() mothod is used to operate on every array item

Syntax of forEach() method

The syntax for forEach() method is as following syntax:
array.forEach(callback(currentvalue,index,arr),thisArg)


Example of Array forEach()

In this example forEach() method is used to print each element in the array.

<script type = "text/javascript">
var arr = ["HTML", "CSS", "JavaScript"];  
  
arr.forEach(function(fetch) {  
  document.writeln(fetch);  
});    
</script>                  
        

Output of above code


Second Example of forEach() method

In this example forEach method is used to print the Fibonacci series.

<script type = "text/javascript">
var sum = 0;  
var arr = [10,18,12,20];  
  
arr.forEach(function myFunction(element) {  
    sum= sum+element;  
  document.writeln(sum);  
});     
</script>                  
        

Output of above code


Note:

Array.forEach() is supported in all browsers except Internet Explorer 8 or earlier:








The Best

Comment here

If you have any query, if you want to know something about any of technical course related to computer science field, if you have any suggestion about relevant to uploaded content or if you anything wrong here (any mistake in content) than please contact us. Keep in mind, comment should be according to community guidelines.