JavaScript – How to loop an Array

In JavaScript, we can use for, forEach or for..of to loop an Array.

1.1 for


	//old-school, classic for loop
	var str = ["a", "b", "c", "d", "e"];
	for(var i =0; i < str.length; i++){
		console.log(str[i]); //a,b,c,d,e
	}

output


a
b
c
d
e

1.2 forEach()


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

	function anyFunction(data){
		console.log(data);
	}

output


1
2
3
4
5

1.3 for..of


	var strArray = ["a", "b", "c", "d", "e"];
	for(var s of strArray){
		console.log(s);
	}

output


a
b
c
d
e

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