Looping Array Elements in JavaScript

Looping through array elements is a common task in JavaScript programming. You may need to access, modify, or perform operations on each element of an array, and JavaScript provides several methods to loop through arrays efficiently.

Using for Loop

The for loop is one of the most basic ways to iterate over an array. It provides full control over the iteration process, allowing you to determine where it starts, stops, and how it moves.

let fruits = ['Apple', 'Banana', 'Orange'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output:
// Apple
// Banana
// Orange

The for loop starts at index 0 and goes up to fruits.length - 1. It prints each element of the array.

Using forEach() Method

The forEach() method is a convenient way to loop through each element of an array. It takes a callback function as an argument and calls it for each element.

fruits.forEach(function(fruit) {
  console.log(fruit);
});
// Output:
// Apple
// Banana
// Orange

The forEach() method makes it easy to work with each element without needing to manage an index.

Using for...of Loop

The for...of loop provides a cleaner syntax to iterate over the elements of an array. It directly works with the elements, which makes the code more readable.

for (let fruit of fruits) {
  console.log(fruit);
}
// Output:
// Apple
// Banana
// Orange

The for...of loop simplifies iteration by providing direct access to the elements without using an index.

Using map() Method

The map() method creates a new array by calling a provided function on every element in the original array. It’s typically used for transforming data.

let upperFruits = fruits.map(function(fruit) {
  return fruit.toUpperCase();
});
console.log(upperFruits);
// Output:
// ['APPLE', 'BANANA', 'ORANGE']

The map() method allows you to create a new array with each element transformed, while leaving the original array unchanged.

Using while Loop

The while loop can also be used to iterate through an array. You can use a counter variable to access elements.

let i = 0;
while (i < fruits.length) {
  console.log(fruits[i]);
  i++;
}
// Output:
// Apple
// Banana
// Orange

The while loop continues as long as the condition is true, making it easy to loop until a certain condition is met.

Using do...while Loop

The do...while loop works similarly to the while loop, but it ensures the loop body runs at least once.

i = 0;
do {
  console.log(fruits[i]);
  i++;
} while (i < fruits.length);
// Output:
// Apple
// Banana
// Orange

The do...while loop will execute the block at least once, regardless of the condition at the start.