JavaScript - Iterate Over an Array
JavaScript for Loop can be used to iterate over an array. The for loop runs for the length of the array and in each iteration it executes the code defined inside. We can access the array elements using the index number.
1. Using for...of Loop
The for…of loop iterates over the values of an iterable object such as an array. It is a better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have a break or continue statements.
let a = [10, 20, 30, 40, 50];
for (let item of a) {
console.log(item);
}
Output
10 20 30 40 50
2. Using forEach() Method
The forEach() Method calls the provided function once for every array element in the order. It does not return a new array and does not modify the original array. It’s commonly used for iteration and performing actions on each array element.
let a = [10, 20, 30, 40, 50];
a.forEach((item) => {
console.log(item);
});
Output
10 20 30 40 50
3. Using for...in Loop
A for...in Loop iterates over the enumerable properties of an object, allowing you to access each key or property name in turn. The for…in loop can also works to iterate over the properties of an array if maintaining index order is important.
let a = [10, 20, 30, 40, 50];
for (let i in a) {
console.log(a[i]);
}
Output
10 20 30 40 50
4. Using for loop
The for Loop executes a set of instructions repeatedly until the given condition becomes false. It is similar to loops in other languages like C/C++, Java, etc.
let a = [10, 20, 30, 40, 50];
for (let i = 0; i < a.length; i++) {
console.log(a[i]);
}
Output
10 20 30 40 50
5. Using while Loop
A while loop in JavaScript is a control flow statement that allows the code to be executed repeatedly based on the given boolean condition.
let a = [10, 20, 30, 40, 50];
let i = 0;
while (i < a.length) {
console.log(a[i]);
i++;
}
Output
10 20 30 40 50
6. Using do...while Loop
The do...while Loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. The do...while loop executes the code at least once.
let a = [10, 20, 30, 40, 50];
let i = 0;
do {
console.log(a[i]);
i++;
} while (i < a.length);
Output
10 20 30 40 50