The for loop in JavaScript is commonly used to iterate through an array. It allows you to process each element one by one using its index.
- The loop runs from 0 to the length of the array − 1.
- Each iteration executes the code inside the loop.
- Array elements are accessed using their 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);
}
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);
});
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]);
}
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]);
}
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++;
}
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);