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.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...ofwhen you just need each value. - Use
forwhen you need the index or more control. - Use
forEach()when you want to run a function for every item. - Use
map()orfilter()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
-
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
true, so the loop runs. -
console.log(numbers[i])becomes:console.log(numbers[0])Output:
10 -
i++increasesito1. -
JavaScript checks again:
1 < 3true, so it logsnumbers[1], which is20. -
ibecomes2. -
JavaScript checks:
2 < 3true, so it logsnumbers[2], which is30. -
ibecomes3. -
JavaScript checks:
3 < 3This 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.
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.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
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
| 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 | No | Yes |
filter() | Keep matching items | Yes | No | Yes |
for vs for...of
- Use
forwhen you need the index or precise loop control. - Use
for...ofwhen 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...initerates over property keys.for...ofiterates over values.- For arrays,
for...ofis usually the better choice.
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. - Use
forfor 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...infor normal array iteration.
Edge cases
- Empty array: the loop body does not run.
forEach()does not supportbreak.map()andfilter()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.
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
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.