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++) {
	    //Develop logic

-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);

-Very short and succinct.

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){

-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