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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar