Loop
Javascript

Loop through an array in JavaScript

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In JavaScript, there are several ways to loop through an array. Here are some of the most common methods:

1. for Loop

The classic for loop gives you control over the index and is suitable when you need to access both the index and value.

javascript
1const array = [1, 2, 3, 4, 5];
2
3for (let i = 0; i < array.length; i++) {
4    console.log(array[i]);
5}

2. for...of Loop (ES6)

The for...of loop iterates directly over the values in the array, making it concise and easy to use.

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

3. forEach() Method

The forEach() method executes a function for each element in the array. It’s concise and functional, often preferred for simple iteration.

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

4. map() Method

The map() method creates a new array by applying a function to each element. It’s useful when you want to transform each element in the array.

javascript
const doubled = array.map(value => value * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

The for...in loop iterates over enumerable properties, including array indices. However, it's generally used for objects, as it may include inherited properties and isn’t ideal for array iteration.

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

Summary

  • Use for or for...of for general iteration.
  • Use forEach() for concise, functional iteration.
  • Use map() when you need to transform elements and return a new array.
  • Avoid for...in for arrays, as it’s primarily intended for objects.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.