javascript foreach

Javascript foreach is applied to get index and value from inside an array. PHP extract data from the database and convert it into a javascript array, and display the data with the javascript foreach loop. You can’t extract the data directly from the database using a javascript loop.

There are many ways to use javascript foreach array, after looking at the examples given below you will find how to use foreach in javascript.

Javascript Foreach

<p id="datalist"></p>
<script>
	var data = ["AXV", "XGY", "KUR"];
	data.forEach(mywebsite);
	function mywebsite(item, index) {
	document.getElementById("datalist").innerHTML += index + ":" + item + "<br>"; 
	}
</script>

Output:- 
0:AXV
1:XGY
2:KUR


<script> 
	function myfunction() { 
		const myitems = [1, 2, 3, 4, 5]; 
		const data = []; 
		myitems.forEach(function(item){ 
			data.push(item); 
		}); 
			document.write(data); 
		} 
		myfunction(); 
</script>

Output:- 1,2,3,4,5

<script>
	var Data = ["AMC", "BHY", "GSE"];
	Data.forEach(element => console.log(element));
</script>

Output:- 
AMC
BHY
GSE

Sum In Array

<p id="myoutput"></p>
<script>
	var data = 0;
	var getdata = [25, 50, 99, 8,20];
	getdata.forEach(mySumFunction);
	function mySumFunction(num) {
		data += num;
		  document.getElementById("myoutput").innerHTML = data;
	}
</script>
Output:- 210

Multiply In Array

<script>
	var data = [15, 12, 18, 20];
	data.forEach(myfunction)
	function myfunction(item, index, multiply) {
	  multiply[index] = item * 2;
	}
	document.write(data); 
</script>
Output:- 30,24,36,40

Javascript Alert

<script>
	var data = [20, 59, 33, 20];
	data.forEach(myfunction)
	function myfunction(item, index, value) {
	  value[index] = item;
	}
	      alert(data); 
</script>

Browser Support

  • Edge
  • Firefox
  • Internet Explorer
  • Opera
  • Safari
  • Chrome

Frequently Asked Questions

We have answers to some questions that people search on the Internet everyday. Let us know what are those questions and what are their answers.

How do I link CSS to HTML?
To link CSS with HTML, you can place your file inside the tag. For example .

How do you put a full background image on HTML?
If you want to apply the full background image, then you can apply the image above your body tag. for example Background-image: url (“myimage.jpg”).

What is div in HTML?
In simple language, div is a box inside which you set your elements.

How do you underline in HTML?
With the tag, you can underline your text.

Where do I put CSS in HTML?
There are 3 ways to apply CSS, either you can link your file inside the tag, or you can add inline CSS, or you can place your CSS on the same page with the

What is text formatting in HTML?
To make the text appear well, the text is formatted with a few HTML tags (i,u,mark).

Note: All the examples you have seen inside this article have all been made by us and tested thoroughly. So you can use all these without any difficulty.