DEV Community

Avnish
Avnish

Posted on

How to Loop Through an Array in JavaScript

Let's cover each topic with examples, detailed explanations, and formatted output.

What are Loops in JavaScript?

Loops in JavaScript are used to execute a block of code repeatedly. They allow you to iterate over data structures like arrays or objects to perform operations on each element or key-value pair.

How to Loop Through an Array in JavaScript:

An array is a common data structure in JavaScript. You can loop through an array using various types of loops.

const array = [1, 2, 3, 4, 5];

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

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

How to Loop Through an Array with a While Loop in JavaScript:

A while loop executes its statements as long as a specified condition evaluates to true.

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

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

How to Loop Through an Array with a do…while Loop in JavaScript:

A do...while loop is similar to a while loop, but the block of code inside the loop will always be executed at least once, even if the condition is false.

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

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

How to Loop Through an Array with a for Loop in JavaScript:

A for loop is commonly used when you know the number of iterations you need.

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

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

How to Loop Through an Array with a for…in Loop in JavaScript:

A for...in loop iterates over the enumerable properties of an object, including array indices. However, it's generally discouraged to use for...in loops with arrays due to potential issues with inherited properties.

for (let index in array) {
  console.log(array[index]);
}

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

How to Loop Through an Array with a for…of Loop in JavaScript:

A for...of loop is used to iterate over iterable objects like arrays, strings, maps, sets, etc.

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

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

How to Loop Through an Array with a forEach Loop in JavaScript:

The forEach method allows you to iterate over array elements and execute a function for each element.

array.forEach(function(element) {
  console.log(element);
});

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

Each of these methods has its own use cases and advantages. Choose the one that fits your requirements and coding style best.

Top comments (0)