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:
forloopfor...offorEach()map()andfilter()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
forloop says: “Start at box 0, then move to 1, then 2...” - A
for...ofloop 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.
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
iby1each time - Access each item with
fruits[i]
2. for...of
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.(fruit);
}
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
-
numbersis created:[10, 20, 30] -
The loop starts with:
let i = 0 -
JavaScript checks the condition:
i < numbers.lengthSince
numbers.lengthis3, this becomes:0 < 3This is , so the loop runs.
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 usernames) {
(username === ) {
.();
}
}
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()) {
.();
;
}
}
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.lengthis3- Valid indexes are
0,1, and2 fruits[3]isundefined
Fix:
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
2. Forgetting that array indexes start at 0
Comparisons
| Approach | Best for | Can access index easily? | Can break/continue? | Returns new array? |
|---|---|---|---|---|
for | Full control | Yes | Yes | No |
for...of | Clean value iteration | Not directly | Yes | No |
forEach() | Run a function for each item | Yes | No | No |
map() | Transform each item | Yes |
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...offor simple value iteration.
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.
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.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.