JavaScript – Array forEach examples

In JavaScript, we can use forEach(function) to loop an Array. The provided function in forEach() will run once for each array element.


	var total = 0;
	var num = [1, 2, 3, 4, 5];
	num.forEach(anyFunction)

	function anyFunction(data){
		total += data;
	}
	
	console.log(total); //15

	var words = "";
	var num = ["a", "b", "c", "d", "e"];
	num.forEach(anyFunction2)

	function anyFunction2(data, index){
		words += data;
		console.log(index + ":" + data); //0:a, 1:b, 2:c, 3:d, 4:e
	}
	
	console.log(words); //abcde

References

Image

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments