In JavaScript, you can use several methods to loop through an array:

The for loop:

var fruits = ["apple", "banana", "cherry"];
for (var i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

The for…of loop (ES6+):

var fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
    console.log(fruit);
}

The forEach() method:

var fruits = ["apple", "banana", "cherry"];
fruits.forEach(function(fruit) {
    console.log(fruit);
});

The forEach() method with arrow function (ES6+):

var fruits = ["apple", "banana", "cherry"];
fruits.forEach(fruit => console.log(fruit));

You can use any of the above methods to loop through an array in JavaScript. The for loop and the for…of loop provide more flexibility and control, while the forEach() method is more concise and easier to read.

Please note that all the above methods will iterate through the array in the same order as the original array. If you want to loop through the array in reverse order, you can use the for loop and start the loop counter at the last index of the array, and decrement the counter by 1 on each iteration.

Also Read:

Categorized in: