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
forloop when you need the index for...ofwhen you want each value directlyforEach()when you want to run a function for every itemmap(),filter(), andreduce()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 oneforEach()= 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.
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:
HelloWorld
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:
fruitsis created as an array with 3 values.- The loop starts:
for (const fruit of fruits). - On the first iteration,
fruitbecomes"apple". console.log(fruit)printsapple.- On the second iteration,
fruitbecomes"banana". console.log(fruit)printsbanana.- On the third iteration,
fruitbecomes"cherry". console.log(fruit)printscherry.- There are no more items, so the loop ends.
Trace table:
| Iteration | Current value of fruit | Output |
|---|---|---|
| 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:
istarts at0.- Check
i < fruits.length→0 < 3is true. - Print
0, "apple". - Increase
ito1. - Check
1 < 3→ true. - Print
1, "banana". - Increase
ito2. - Check
2 < 3→ true. - Print
2, "cherry". - Increase
ito3. - Check
3 < 3→ false. - 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);
}
}
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.lengthis3- valid indexes are
0,1, and2 arr[3]isundefined
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
| Approach | Best for | Gives value directly? | Gives index easily? | Can break/continue? | Returns new array? |
|---|---|---|---|---|---|
for | Full control | No, use arr[i] | Yes | Yes | No |
for...of | Clean value iteration | Yes | No | Yes | No |
forEach() | Simple side effects | Yes | Yes, as 2nd argument | No | No |
map() | Transforming items | Yes | Yes, as 2nd argument | No | Yes |
for...in | Object keys or property names | No | Sort of, but as keys | Yes | No |
for...of vs forEach()
- Use
for...ofwhen you may needbreak,continue, orawait. - Use
forEach()for short, simple operations on every element.
for vs for...of
- Use
forwhen index control matters. - Use
for...ofwhen 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
}
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...ofiterates over valuesfor...initerates over keys/property namesforEach()cannot usebreakorcontinuemap()should be used when you want a new array- Classic
forloops are best when you need index control
Edge cases
- Empty array: loop body runs zero times
array.lengthis one more than the last valid indexforEach()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...ofoverforEach()
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...offor simple value iteration - use
forwhen 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.
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
- Create an array with at least three task names.
- Use
for...ofto print each task name. - Use a classic
forloop to print each task with its index. - Use
map()to create a new uppercase version of the 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.