How to Use For Each loop in JavaScript

For Each Loop In JavaScript

Hello Guys,
Having trouble in understanding the concept of the for each loop in javascript. or having trouble finding the correct source code. Then don't worry this post is for you.
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

Comments

Popular posts from this blog

C/C++ program to check the Palindrome string.

Second Equation of motion, How to implement using C language

Third Equation of motion, How to implement using C language