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

About the Author

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

Comments

avatar