In JavaScript, there are several ways to iterate over an array. Here are some of the ways you can use to iterate the JavasScript array:
1. For Loop
JavaScript
var array = [1, 2, 3, 4, 5];
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
2. For…of Loop
JavaScript
var array = [1, 2, 3, 4, 5];
for (var element of array) {
console.log(element);
}
3. forEach Loop
JavaScript
var array = [1, 2, 3, 4, 5];
array.forEach(function (element) {
console.log(element);
});
using an arrow function:
JavaScript
var array = [1, 2, 3, 4, 5];
array.forEach((element) => {
console.log(element);
});
4. Map Method
JavaScript
var array = [1, 2, 3, 4, 5];
array.map(function (element) {
console.log(element);
});
using an arrow function:
JavaScript
var array = [1, 2, 3, 4, 5];
array.map((element) => {
console.log(element);
});
5. For…in Loop (not recommended for arrays)
JavaScript
var array = [1, 2, 3, 4, 5];
for (var index in array) {
console.log(array[index]);
}