What is the use of forEach() method in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Array iteration:It is nothing but to check each and every element in an array according to requirement of the function.

forEach()

The forEach() method calls function once for every element in an array. Below are two examples to show the method.

Example-1

 Live Demo

<html>
<body>
<p id="each"></p>
<script>
   var num = "";
   var values = [1,2,3,4,5];
   values.forEach(myArray);
   document.getElementById("each").innerHTML = num;
function myArray(value, index, array) {
num = num + value + "<br>";
}
</script>
</body>
</html>

Output

1
2
3
4
5

Example-2

 Live Demo

<html>
<body>
<script>
   var array = ['Ram', 'Rahim', 'Remo'];
   array.forEach(function(e) {
      document.write(e);
      document.write("</br>");
   });
</script>
</body>
</html>

Output

Ram
Rahim
Remo
raja
Published on 23-May-2019 09:17:21
Advertisements