Summary: In this tutorial, you will learn different ways to loop over an array in JavaScript with the help of the examples.

There are several ways to loop over an array in JavaScript. Here are a few common methods:

1. for loop

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

This is a traditional looping structure that allows you to specify a loop counter and a loop condition. In this example, the loop counter is i, which is initialized to 0.

The loop condition is i < array.length, which means that the loop will continue as long as i is less than the length of the array.

Inside the loop, the code logs the element at the current index (array[i]) to the console. After the code inside the loop has been executed, the loop counter is incremented by 1 (i++).

2. for...of loop

for (const element of array) {
  console.log(element);
}

This is a new type of loop introduced in ECMAScript 6 (ES6) that allows you to iterate over the elements of an array.

The for...of loop uses the of keyword to iterate over the elements of the array, and the variable element is used to hold the value of the current element. Inside the loop, the code logs the current element (element) to the console.

3. forEach() method

array.forEach(element => {
  console.log(element);
});

This is a method of the Array object that allows you to iterate over the elements of an array.

The forEach() method takes a callback function as an argument, and this function is called for each element in the array.

In this example, the callback function uses an arrow function syntax and has a single parameter (element), which holds the value of the current element. Inside the callback function, the code logs the current element (element) to the console.

4. while loop

let i = 0;
while (i < array.length) {
  console.log(array[i]);
  i++;
}

This is another traditional looping structure that allows you to specify a loop condition.

In this example, the loop condition is i < array.length, which means that the loop will continue as long as i is less than the length of the array.

The loop counter (i) is initialized to 0 before the loop starts. Inside the loop, the code logs the element at the current index (array[i]) to the console and then increments the loop counter by 1 (i++).

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply