Java vs JavaScript: enhanced for loop and forEach() explained
Java for-each / enhanced for loop
Wiki topics:
🌐 · Web Development
Java vs JavaScript: enhanced for loop and forEach() explained
Java for-each / enhanced for loop
syntax
for(dataType variable : collection){
}
- Used to iterate over arrays and collections.
- Simple and more readable than traditional loop.
- No need to use index of elements.
- Provide only values not indexes
- Always iterating over all elements from first to last.
- Can use
breakorcontinue
Limitations
- Cannot iterate in reverse order
- Cannot directly access the index of element
- Cannot modify elements directly
example with array
int numbers[] = {1,2,3,4};
for(int num: numbers){
System.out.println(num);
}
example with collection
List<String> names = Arrays.asList("Dog", "Cat","Elephant");
for(String name: names){
System.out.println(name);
}
Java forEach() method
- Not a loop; Method provided by Iterable interface
- Cannot use
breakorcontinue - Can modify elements
List<String> names = Arrays.asList("Dog", "Cat","Elephant");
names.forEach(System.out::println); // used method reference
List<String> names = Arrays.asList("Dog", "Cat","Elephant");
names.forEach(name -> System.out.println(name)); // used lambda function
JavaScript for-each / for ….of / enhanced for loop
syntax
for( const variable of array){
}
- Used to iterate over arrays, strings, maps, sets
- Simple and more readable than traditional loop.
- Provide only values not indexes
- Can use
breakorcontinue
Limitations
- Cannot iterate in reverse order
- Cannot directly access the index of element
example with array
const numbers = [1,2,3,4];
for(const num of numbers){
console.log(num);
}
const names = ["Dog", "Cat", "Elephant"];
for(const name of names){
console.log(name);
}
JavaScript forEach() method
- Cannot use
breakorcontinueorreturn - Can access index
- Can modify elements
const names = ["Dog", "Cat", "Elephant"];
names.forEach(name => console.log(name));
JavaScript for ….in loop
syntax
for(const key in object){
}
- Used to iterate over enumerable keys
- Provide only keys not values
- Best for objects, not recommended for arrays
- Can use
breakorcontinue
const person = {
name: "Harry",
age: 59
};
for (const key in person) {
console.log(key + " > " + person[key]);
} 메타데이터
- post_id
- 8fc05dfa3d60
- slug
- java-vs-javascript-enhanced-for-loop-and-foreach-explained-8fc05dfa3d60
- url
- https://medium.com/@rwijayabandu/java-vs-javascript-enhanced-for-loop-and-foreach-explained-8fc05dfa3d60
- canonical_url
- https://medium.com/@rwijayabandu/java-vs-javascript-enhanced-for-loop-and-foreach-explained-8fc05dfa3d60
- author_url
- https://medium.com/@rwijayabandu
- status
- ok
- fetched_at
- 2026-08-19 20:12:43