Iterate JS Arrays: for, for...of vs Java Enhanced For
Learn to loop through arrays in JavaScript with for loops, for...of (Java enhanced for equivalent), and forEach. Examples, comparisons, sparse arrays handling, and best practices for iteration.
How to iterate through arrays in JavaScript using for loops?
In Java, you can use an enhanced for loop to traverse objects in an array:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
What are the equivalent methods for looping through arrays in JavaScript, and how do they compare to Java’s enhanced for loop?
Loop through arrays in JavaScript using the classic for loop for index control, the for…of loop as the direct equivalent to Java’s enhanced for loop, or Array.prototype.forEach() for functional-style iteration. For…of iterates over values cleanly—like Java’s for (String s : array)—and supports break or continue for early exits, making it ideal for most array traversals. Traditional for loops shine when you need the index, while forEach skips breaks but keeps code declarative.
Contents
- Java’s Enhanced For Loop Recap
- Traditional For Loop in JavaScript
- For…of: The Closest Java Equivalent
- Array.prototype.forEach()
- Other Array Iteration Options
- Comparison Table: JS Loops vs Java Enhanced For
- Sources
- Conclusion
Java’s Enhanced For Loop Recap
Java’s enhanced for loop, introduced in JDK 5, simplifies iteration over arrays or collections by giving you direct access to elements without manual indexing. Your example nails it:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something with s
}
No more i < length boilerplate. It pulls values sequentially, handles the iteration under the hood, and works great unless you need the index or mutation control. But JavaScript? It lacks this exact syntax—until ES6 brought us close. Why care about equivalents? Because JS arrays are dynamic, sparse arrays exist, and you might switch languages mid-project.
Traditional For Loop in JavaScript
Ever need full control over the index? The classic for loop is your go-to for iterating through arrays in JavaScript. It’s verbose but predictable, just like C-style loops everywhere.
const myArray = ["Hello", "World"];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]); // Outputs: Hello, then World
}
This mirrors low-level array access. Want to skip elements? Tweak i. Modifying the array mid-loop? No problem—indexing stays reliable. But it’s wordy. And on sparse arrays (gaps like arr[0] = 1; arr[100] = 2), it runs length times, hitting undefined for holes. MDN’s loops guide calls it the most explicit option. Use it when index matters—like swapping elements or processing in chunks.
Performance-wise, it’s often fastest for huge arrays since no callbacks or iterators overhead.
For…of: The Closest Java Equivalent
Here’s where JavaScript gets elegant. The for...of loop, from ES6, iterates over values directly—making it the spiritual successor to Java’s enhanced for loop. No indices, just elements.
const myArray = ["Hello", "World"];
for (const s of myArray) {
console.log(s); // Hello, World—exactly like Java
}
Boom. It calls the array’s iterator ([Symbol.iterator]()), yielding {value, done} pairs until finished. Break out early? break works. Skip one? continue. Even cleans up via return() on early exits. MDN’s for…of reference confirms: perfect for arrays, strings, Sets—any iterable.
Compared to Java? Both value-focused, readable, breakable. JS wins on generality (iterables beyond arrays). Downside: no built-in index (grab it separately if needed). Sparse arrays? It skips holes smartly, unlike plain for.
In practice, this is my default for simple traversals. Why fight indices when you don’t need them?
Array.prototype.forEach()
Functional programming fans, meet forEach(). It calls a callback on each element—clean, declarative, no mutable loop vars.
const myArray = ["Hello", "World"];
myArray.forEach((s, index) => {
console.log(`${index}: ${s}`);
});
Gets value and index automatically. But here’s the catch: no break or return to exit early. It runs to completion. W3Schools and freeCodeCamp highlight this for side effects like logging or DOM updates.
Sparse arrays? It only hits defined indices. Great for chaining with map or filter, but stick to loops if control flow matters.
Other Array Iteration Options
Don’t stop at basics. for...in tempts with syntax similarity, but Stack Overflow warns: it’s for property keys, not values. Arrays inherit toString etc., so it iterates extras—avoid for arrays.
Transformers like map, filter, reduce shine for new arrays:
const doubled = myArray.map(s => s.length * 2); // Functional power
GeeksforGeeks praises for...of for simplicity, but these win for immutability. Performance? For huge data, benchmark—loops edge out methods per TechEmpower-style tests, but readability trumps micro-optimizations.
Browser support? for...of is everywhere post-IE now (2026 standards).
Comparison Table: JS Loops vs Java Enhanced For
| Feature | Java Enhanced For | JS Traditional For | JS for…of | JS forEach() |
|---|---|---|---|---|
| Access | Values only | Index → value | Values | Value + index |
| Break/Continue | Yes | Yes | Yes | No |
| Sparse Arrays | N/A (dense) | Hits undefined | Skips holes | Skips holes |
| Index Needed? | No | Manual | Add counter | Built-in param |
| Mutability | Can mutate loop var | Full control | Loop var scoped | Callback scope |
| Best For | Simple iteration | Index ops | Java-like loops | Side effects |
Data from MDN and Stack Overflow. Pick for...of for that Java feel.
Sources
- Loops and iteration - JavaScript | MDN
- for…of - JavaScript | MDN
- Loop through an array in JavaScript - Stack Overflow
- Does Javascript have an enhanced for loop syntax similar to Java’s - Stack Overflow
- How to Iterate Over an Array - GeeksforGeeks
- How to Loop Through an Array in JavaScript – JS Iterate Tutorial - freeCodeCamp
- JavaScript Array Iteration - W3Schools
- How to Loop Through an Array in JavaScript – Flexiple
Conclusion
For iterating through arrays in JavaScript, for...of delivers the cleanest match to Java’s enhanced for loop—values direct, breakable, iterable-agnostic. Fall back to traditional for when indices rule, or forEach for callback bliss. Test in your context: readability often beats raw speed. Grab these patterns, and your JS arrays won’t feel foreign anymore.