Introduction

In this blog post we will learn about the foreach loop in javascript if you are new to javascript please see this. Folks who haven’t used since long time here is the refresher.

jslogo

What is For Each Loop:

this is the loop which automatically iterates through all the elements of an array, it helps in the working with the dynamic array.

Let’s start working.

In javascript for-each loop works in a different way.

Here we have to create a function which will be passed to the foreach function of the array.

Enough discussion.

Start working.

First, create an array of names of the actor.

var heros = ["Tony","Captain","Batman","SuperMan"]  

Now create the function with the logic that has to be passed in the for each loop.

function myfunc(item){  
 console.log(item + " is a very good superhero");  
}

 Now call the function in the foreach function of array

// running the foreach loop 4 times  
heros.forEach(myfunc);  

You can run this code into the node.js but we are going to use google chrome.
to do this we have to create an HTML file with little code and add this javascript file to that HTML file.

<!DOCTYPE html>  
<html>  
<head>  
<title>test</title>  
</head>  
<body>  
</body>  
<script type="text/javascript" src="deck.js"></script>  
</html>

Now run this HTML page.
to see the output of the javascript open the console using the.
ctrl+shift+i in google chrome.

full code for the javascript is

var heros = ["Tony","Captain","Batman","SuperMan"]  
// function that will through each time  
function myfunc(item){  
 console.log(item + " is a very good superhero");  
}  
// running the foreach loop 4 times  
heros.forEach(myfunc);  
  
  
// this is how for each loop works in javascript  

Here is my output of the console.

output