Question

How to Loop Through an Array in JavaScript

javascriptarraysloopsfor-loop

Question

In Java, you can traverse the elements of an array using an enhanced for loop like this:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

Can you do something similar in JavaScript to loop through each item in an array? If so, what are the common ways to do it, and how do they differ?

Short Answer

By the end of this page, you will understand how to loop through arrays in JavaScript using for, for...of, forEach, and related methods. You will also learn when to use each approach, how they behave, and which beginner mistakes to avoid.

Concept

In JavaScript, arrays hold ordered collections of values, and looping lets you process each value one at a time. This is one of the most common tasks in programming.

Java has an enhanced for loop for iterating over array elements. JavaScript has a similar feature with for...of, but it also offers several other common patterns:

  • A classic for loop when you need the index
  • for...of when you want each value directly
  • forEach() when you want to run a function for every item
  • map(), filter(), and reduce() when you want to transform or process data functionally

This matters because choosing the right loop makes code:

  • easier to read
  • less error-prone
  • more expressive
  • better suited to the task

For example, if you only want to print every item, for...of is simple. If you want to build a new array, map() is often better than manually pushing values inside a loop.

Mental Model

Think of an array like a row of labeled boxes:

  • box 0 contains "Hello"
  • box 1 contains "World"

A loop is like walking past each box and looking inside.

Different loop styles change how you walk:

  • for = you walk by box number: 0, 1, 2...
  • for...of = you just pick up each value one by one
  • forEach() = you hand each item to a helper function

So if Java's enhanced for loop says, “give me each element,” JavaScript's for...of says almost the same thing.

Take Quiz

Syntax and Examples

Common ways to loop through an array

1. for...of — closest to Java's enhanced for

const myStringArray = ["Hello", "World"];

for (const s of myStringArray) {
  console.log(s);
}

This prints each value directly:

  • Hello
  • World

Use this when you want the items and do not need the index.

2. Classic for loop

const myStringArray = ["Hello", "World"];

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

Use this when you need:

  • the index
  • more control over start, stop, or step size

3. forEach()

const myStringArray = ["Hello", "World"];

myStringArray.forEach(function (s) {
  console.log(s);
});

You can also use an arrow function:

myStringArray.forEach((s) => {
  console.log(s);
});

This is clean for simple side effects like logging, updating the UI, or calling a function.

4. Getting both index and value

const myStringArray = ["Hello", "World"];

myStringArray.forEach((value, index) => {
  console.log(index, value);
});

Output:

0 "Hello"
1 "World"

5. When you want a new array: map()

const words = ["Hello", "World"];
const uppercased = words.map((word) => word.toUpperCase());

console.log(uppercased);

Output:

["HELLO", "WORLD"]

Use map() when the goal is to create a transformed array, not just loop.

Step by Step Execution

Consider this example:

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

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

Here is what happens step by step:

  1. fruits is created as an array with 3 values.
  2. The loop starts: for (const fruit of fruits).
  3. On the first iteration, fruit becomes "apple".
  4. console.log(fruit) prints apple.
  5. On the second iteration, fruit becomes "banana".
  6. console.log(fruit) prints banana.
  7. On the third iteration, fruit becomes "cherry".
  8. console.log(fruit) prints cherry.
  9. There are no more items, so the loop ends.

Trace table:

IterationCurrent value of fruitOutput
1"apple"apple
2"banana"banana
3"cherry"cherry

Now compare with a classic for loop:

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

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

Step by step:

  1. i starts at 0.
  2. Check i < fruits.length → 0 < 3 is true.
  3. Print 0, "apple".
  4. Increase i to 1.
  5. Check 1 < 3 → true.
  6. Print 1, "banana".
  7. Increase i to 2.
  8. Check 2 < 3 → true.
  9. Print 2, "cherry".
  10. Increase i to 3.
  11. Check 3 < 3 → false.
  12. Loop ends.

Real World Use Cases

Looping through arrays appears everywhere in JavaScript code.

Common examples

Rendering a list of products

const products = ["Keyboard", "Mouse", "Monitor"];

for (const product of products) {
  console.log(`Product: ${product}`);
}

Validating user input values

const fields = ["email", "password", "username"];

fields.forEach((field) => {
  console.log(`Checking ${field}`);
});

Converting API data

const prices = [10, 20, 30];
const formatted = prices.map((price) => `$${price.toFixed(2)}`);

Searching for a matching item

const users = ["Ana", "Sam", "Lee"];

for (const user of users) {
  if (user === "Sam") {
    console.log("Found user");
    break;
  }
}

Processing file or log entries

const lines = ["INFO: Start", "ERROR: Failed", "INFO: End"];

for (const line of lines) {
  if (line.startsWith("ERROR")) {
    console.log(line);
  }
}
Take Quiz

Real Codebase Usage

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

Common patterns

Use for...of for readable iteration

for (const item of items) {
  processItem(item);
}

This is common when code needs to:

  • read each item
  • stop early with break
  • skip items with continue

Use forEach() for simple side effects

items.forEach((item) => logItem(item));

This is often used for:

  • logging
  • updating state
  • calling a helper for every item

Use map() for transformation

const names = users.map((user) => user.name);

This is preferred over manually building arrays because it clearly communicates intent.

Guard clauses inside loops

for (const user of users) {
  if (!user.email) continue;
  sendEmail(user.email);
}

This keeps the main logic cleaner.

Validation before processing

if (!Array.isArray(items)) {
  throw new Error("items must be an array");
}

for (const item of items) {
  processItem(item);
}

This helps avoid runtime errors.

Early return or early exit

for (const item of items) {
  if (item.isInvalid) {
    return false;
  }
}

return true;

This is common in validation logic.

Async caution

Developers are careful with forEach() when using async/await, because forEach() does not wait the way beginners often expect. In many cases, for...of is the better choice for sequential async work.

Common Mistakes

1. Using for...in for array values

for...in loops over property names, not the actual values.

const arr = ["Hello", "World"];

for (const x in arr) {
  console.log(x);
}

Output:

0
1

This gives indexes as strings, not the array items.

Better:

for (const x of arr) {
  console.log(x);
}

2. Off-by-one errors in classic for loops

Broken code:

const arr = ["a", "b", "c"];

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

Problem:

  • arr.length is 3
  • valid indexes are 0, 1, and 2
  • arr[3] is undefined

Fix:

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

3. Forgetting that forEach() cannot use break

Broken idea:

arr.forEach((item) => {
  if (item === "stop") {
    break;
  }
});

This is invalid because break does not work inside forEach() callbacks.

Use for...of instead:

for (const item of arr) {
  if (item === "stop") {
    break;
  }
}

4. Using map() when you do not need a new array

Less appropriate:

arr.map((item) => console.log(item));

map() is meant to create and return a new array. If you only want side effects, use forEach() or for...of.

5. Modifying the wrong variable

Broken code:

const arr = [1, 2, 3];

for (const item of arr) {
  item = item * 2;
}

This fails because item is a const loop variable.

If you want a new array:

const doubled = arr.map((item) => item * 2);

If you want to update by index:

for (let i = 0; i < arr.length; i++) {
  arr[i] = arr[i] * 2;
}

Comparisons

ApproachBest forGives value directly?Gives index easily?Can break/continue?Returns new array?
forFull controlNo, use arr[i]YesYesNo
for...ofClean value iterationYesNoYesNo
forEach()Simple side effectsYesYes, as 2nd argumentNoNo
map()Transforming itemsYesYes, as 2nd argumentNoYes
for...inObject keys or property namesNoSort of, but as keysYesNo

for...of vs forEach()

  • Use for...of when you may need break, continue, or await.
  • Use forEach() for short, simple operations on every element.

for vs for...of

  • Use for when index control matters.
  • Use for...of when readability matters and you only need values.

Java enhanced for vs JavaScript

Java's enhanced loop:

for (String s : myStringArray) {
    // Do something
}

Closest JavaScript equivalent:

for (const s of myStringArray) {
  // Do something
}
Take Quiz

Cheat Sheet

Quick reference

Loop through values

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

Loop through indexes and values

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

Use forEach()

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

Create a new transformed array

const newArray = array.map((item) => item * 2);

Rules to remember

  • for...of iterates over values
  • for...in iterates over keys/property names
  • forEach() cannot use break or continue
  • map() should be used when you want a new array
  • Classic for loops are best when you need index control

Edge cases

  • Empty array: loop body runs zero times
  • array.length is one more than the last valid index
  • forEach() skips empty slots in sparse arrays in a different way than some loops, so be careful with unusual arrays
  • For async sequential work, prefer for...of over forEach()

FAQ

Can JavaScript do the same kind of array loop as Java's enhanced for loop?

Yes. The closest equivalent is for...of.

What is the best way to loop through an array in JavaScript?

It depends on the goal:

  • use for...of for simple value iteration
  • use for when you need the index
  • use forEach() for simple side effects
  • use map() when creating a new array

Should I use for...in for arrays in JavaScript?

Usually no. for...in is for property names, not normal array value iteration.

How do I get both index and value while looping?

Use either a classic for loop or forEach((value, index) => ...).

Can I stop a forEach() loop early?

No. If you need to stop early, use for, for...of, or methods like some() or find() depending on the problem.

Is for...of supported in modern JavaScript?

Yes, it is part of modern JavaScript and widely used.

When should I use map() instead of a loop?

Use map() when your goal is to convert each item into a new value and return a new array.

Take Quiz

Mini Project

Description

Build a small script that processes a list of task names. This project demonstrates different ways to loop through an array in JavaScript and helps you practice reading values, using indexes, and creating a transformed array.

Goal

Create a script that prints each task, shows its position, and generates a second array with all task names converted to uppercase.

Requirements

  1. Create an array with at least three task names.
  2. Use for...of to print each task name.
  3. Use a classic for loop to print each task with its index.
  4. Use map() to create a new uppercase version of the array.
Take Quiz

Keep learning

Related questions

View more