Question

How to Loop Through an Array in JavaScript

javascriptarraysloopsforeachiteration

Question

How can I loop through all the entries in an array using JavaScript?

Short Answer

By the end of this page, you will understand several ways to iterate over arrays in JavaScript, including for, for...of, and forEach(). You will also learn when to use each approach, how they behave, and which beginner mistakes to avoid.

Concept

In JavaScript, looping through an array means visiting each item one at a time so your code can read it, print it, transform it, validate it, or use it in some other operation.

Arrays are ordered collections, so iteration is one of the most common tasks in JavaScript. For example, you might:

  • display a list of products
  • calculate a total price
  • validate form input values
  • send data items to an API
  • build a new array from an existing one

JavaScript provides multiple ways to loop through an array. The most common are:

  • for loop
  • for...of
  • forEach()
  • map() and filter() for transformation tasks

The main idea is simple: start at the first element, move through the array one element at a time, and stop when there are no more items.

This matters because iteration is everywhere in programming. Once you understand array loops, you can work with lists of users, files, messages, products, numbers, and many other kinds of data.

Mental Model

Think of an array like a row of numbered boxes on a shelf.

  • Each box holds one value.
  • The first box is at position 0.
  • A loop is like walking past the shelf and looking into each box one by one.

Some loop styles make you track the box number yourself, while others simply hand you each item in order.

  • A for loop says: “Start at box 0, then move to 1, then 2...”
  • A for...of loop says: “Just give me each item, one at a time.”
  • forEach() says: “Run this function once for every item.”

All three can process the same array, but they feel slightly different to write and use.

Take Quiz

Syntax and Examples

Common ways to loop through an array

1. Classic for loop

const fruits = ["apple", "banana", "orange"];

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

This uses an index variable i.

  • Start at 0
  • Continue while i < fruits.length
  • Increase i by 1 each time
  • Access each item with fruits[i]

2. for...of

const fruits = ["apple", "banana", "orange"];

for (const fruit of fruits) {
  console.log(fruit);
}

This is often the easiest way to read values from an array.

  • No manual index handling
  • Cleaner syntax for simple iteration

3. forEach()

const fruits = ["apple", "banana", "orange"];

fruits.forEach(function (fruit) {
  console.log(fruit);
});

You can also write it with an arrow function:

const fruits = ["apple", "banana", "orange"];

fruits.forEach((fruit) => {
  console.log(fruit);
});

forEach() runs a callback function once for each element.

4. Accessing both index and value

const fruits = ["apple", "banana", "orange"];

fruits.forEach((fruit, index) => {
  console.log(index, fruit);
});

Output:

0 "apple"
1 "banana"
2 "orange"

When should beginners use which one?

  • Use for...of when you just need each value.
  • Use for when you need the index or more control.
  • Use forEach() when you want to run a function for every item.
  • Use map() or filter() when creating a new array.

Step by Step Execution

Consider this example:

const numbers = [10, 20, 30];

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

Step-by-step

  1. numbers is created:

    [10, 20, 30]
    
  2. The loop starts with:

    let i = 0
    
  3. JavaScript checks the condition:

    i < numbers.length
    

    Since numbers.length is 3, this becomes:

    0 < 3
    

    This is true, so the loop runs.

  4. console.log(numbers[i]) becomes:

    console.log(numbers[0])
    

    Output:

    10
    
  5. i++ increases i to 1.

  6. JavaScript checks again:

    1 < 3
    

    true, so it logs numbers[1], which is 20.

  7. i becomes 2.

  8. JavaScript checks:

    2 < 3
    

    true, so it logs numbers[2], which is 30.

  9. i becomes 3.

  10. JavaScript checks:

    3 < 3
    

    This is false, so the loop stops.

Final output

10
20
30

Real World Use Cases

Looping through arrays is used constantly in real JavaScript programs.

Rendering UI data

const products = ["Laptop", "Phone", "Tablet"];

products.forEach((product) => {
  console.log(`Render product: ${product}`);
});

This pattern is common when displaying lists in web apps.

Calculating totals

const prices = [10, 20, 30];
let total = 0;

for (const price of prices) {
  total += price;
}

console.log(total); // 60

Useful for shopping carts, reports, and analytics.

Validating data

const usernames = ["alice", "", "charlie"];

for (const username of usernames) {
  if (username === "") {
    console.log("Invalid username found");
  }
}

Helpful when checking user input or imported data.

Transforming data

const names = ["alice", "bob"];
const upperNames = names.map((name) => name.toUpperCase());

console.log(upperNames); // ["ALICE", "BOB"]

This is common in APIs, formatting, and data pipelines.

Take Quiz

Real Codebase Usage

In real projects, developers choose array iteration styles based on intent.

Read-only processing

When code only needs to read each item, for...of is often the clearest choice.

for (const user of users) {
  console.log(user.email);
}

Index-based logic

If you need to compare neighboring items or update specific positions, a classic for loop is useful.

for (let i = 0; i < items.length; i++) {
  console.log(`Item ${i}:`, items[i]);
}

Validation with early exit

A classic for loop or for...of works well when you want to stop early.

for (const email of emails) {
  if (!email.includes("@")) {
    console.log("Invalid email found");
    break;
  }
}

forEach() is not ideal here because it does not support break in the normal loop sense.

Data transformation

Developers usually prefer map() when the goal is to create a new array.

const ids = users.map((user) => user.id);

Filtering

Use filter() when only some items should remain.

const activeUsers = users.filter((user) => user.active);

Guard clauses inside loops

for (const file of files) {
  if (!file) continue;
  console.log(file.name);
}

This keeps loop bodies simpler and easier to read.

Common Mistakes

1. Using <= instead of <

Broken code:

const fruits = ["apple", "banana", "orange"];

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

Problem:

  • fruits.length is 3
  • Valid indexes are 0, 1, and 2
  • fruits[3] is undefined

Fix:

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

2. Forgetting that array indexes start at 0

Broken code:

const fruits = ["apple", "banana", "orange"];
console.log(fruits[1]); // banana

A beginner might expect apple, but index 0 is the first item.

3. Using for...in for arrays

const fruits = ["apple", "banana", "orange"];

for (const key in fruits) {
  console.log(key);
}

This prints indexes as strings, not the values directly.

Output:

"0"
"1"
"2"

Use for...of if you want values:

for (const fruit of fruits) {
  console.log(fruit);
}

4. Expecting forEach() to return a new array

Broken idea:

const numbers = [1, 2, 3];
const result = numbers.forEach((n) => n * 2);

console.log(result); // undefined

Use map() instead:

const result = numbers.map((n) => n * 2);
console.log(result); // [2, 4, 6]

5. Trying to break from forEach()

Broken code:

[1, 2, 3].forEach((n) => {
  if (n === 2) break;
  console.log(n);
});

This causes an error because break does not work inside forEach() callbacks.

Use for...of instead:

for (const n of [1, 2, 3]) {
  if (n === 2) break;
  console.log(n);
}

Comparisons

ApproachBest forCan access index easily?Can break/continue?Returns new array?
forFull controlYesYesNo
for...ofClean value iterationNot directlyYesNo
forEach()Run a function for each itemYesNoNo
map()Transform each itemYesNoYes
filter()Keep matching itemsYesNoYes

for vs for...of

  • Use for when you need the index or precise loop control.
  • Use for...of when you just want each value in a readable way.

forEach() vs map()

  • Use forEach() for side effects like logging or updating external state.
  • Use map() when you want a new array based on the original one.

for...in vs for...of

  • for...in iterates over property keys.
  • for...of iterates over values.
  • For arrays, for...of is usually the better choice.
Take Quiz

Cheat Sheet

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

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

// forEach
array.forEach((item, index) => {
  console.log(index, item);
});

// map creates a new array
const newArray = array.map((item) => item * 2);

// filter keeps matching items
const filtered = array.filter((item) => item > 10);

Quick rules

  • Arrays use zero-based indexes.
  • Last valid index is array.length - 1.
  • Use < array.length, not <= array.length.
  • Use for...of for simple value iteration.
  • Use for for index control or early exit logic.
  • Use forEach() for side-effect operations.
  • Use map() to transform arrays.
  • Use filter() to remove unwanted items.
  • Avoid for...in for normal array iteration.

Edge cases

  • Empty array: the loop body does not run.
  • forEach() does not support break.
  • map() and filter() return new arrays; they do not modify by default.

FAQ

How do I loop through an array in JavaScript?

You can use a for loop, for...of, or forEach(). For simple value iteration, for...of is often the easiest to read.

What is the best way to iterate over an array in JavaScript?

It depends on your goal. Use for...of for readability, for for index control, and map() or filter() when creating new arrays.

Should I use forEach() or for...of?

Use forEach() when you want to run a callback for every item. Use for...of if you may need break, continue, or simpler control flow.

Why does my loop go out of bounds?

This usually happens when using <= array.length instead of < array.length. The highest valid index is array.length - 1.

Can I get both the index and the value while looping?

Yes. With forEach(), use (value, index). With a for loop, use array[i]. You can also use other patterns when needed.

Why is for...in not recommended for arrays?

Because it iterates over keys rather than values and is mainly meant for object properties. For arrays, for...of is usually a better fit.

Which loop should I use if I want to stop early?

Use a for loop or for...of. forEach() does not support break in the normal way.

Take Quiz

Mini Project

Description

Build a small script that processes a list of student names. This project demonstrates how to loop through an array, access each item, and also work with both values and indexes.

Goal

Create a program that prints each student name and its position in the array, then creates a second array with all names in uppercase.

Requirements

  • Create an array of at least four student names.
  • Loop through the array and print each name.
  • Print both the index and the value for each student.
  • Create a new array where every name is converted to uppercase.
  • Print the final uppercase array.
Take Quiz

Keep learning

Related questions

View more