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.
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.
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()}`);
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);
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.; i++) {
.(arr[i]);
}
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 |
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 values- iterates over keys/property names
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.
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
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.