How to loop an array in JavaScript?

Photo of author
Written By geekerhub

Lorem ipsum dolor sit amet consectetur pulvinar ligula augue quis venenatis. 

Three main options:

Option 1. Sequential for loop:
for (var i = 0; i < xs.length; i++) { console.log(xsarray[i]); }

<script type="text/javascript">
	var xsarray 	= ["Hello","World", "Success"];
	var arrayLength = xsarray.length;
	for (var i = 0; i < arrayLength; i++) {
	    console.log(xsarray[i]);
	    //Develop logic
	}
</script>

Pros
-Works on every environment
-You can use break and continue flow control statements

Option 2. Array.prototype.forEach:
xs.forEach((x, i) => console.log(x));

<script type="text/javascript">
	const array = ["Hello","World", "Success"];
	array.forEach(function (item, index) {
	  console.log(item, index);
	});
</script>

Pros
-Very short and succinct.
-Declarative

Option 3. ES6 for-of statement:
for (const x of xs) { console.log(x); }

<script type="text/javascript">
	let colors = ['red', 'green', 'blue'];
	for (const color of colors){
	    console.log(color);
	}
</script>

Pros
-It can iterate over a large variety of objects.
-Can use normal flow control statements (break/continue).
-Useful to iterate serially asynchronous values.

Leave a Comment