JavaScript Array Iteration
8 April 2025 | Category: JavaScript
Array iteration in JavaScript means looping through each item in an array and performing actions like displaying data, modifying values, or filtering elements.
JavaScript offers several powerful methods for iterating over arrays.
✅ 1. for
Loop – Traditional Way
The classic for
loop gives full control over the iteration process.
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
🔹 Best when you need access to the index or want to break/continue early.
✅ 2. forEach()
– Easy and Clean
forEach()
executes a function once for each array item.
let colors = ["Red", "Green", "Blue"];
colors.forEach(function(color) {
console.log(color);
});
Or with arrow function:
colors.forEach(color => console.log(color));
🔹 You can’t use
break
orreturn
to exit early inforEach()
.
✅ 3. for...of
Loop – Simple and Readable
for...of
iterates over array values directly.
let scores = [80, 90, 70];
for (let score of scores) {
console.log(score);
}
🔹 Cleaner than
for
, and supportsbreak
andcontinue
.
✅ 4. map()
– Create a New Array
map()
creates a new array by applying a function to each element.
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
🔹 Perfect when you need to transform array data.
✅ 5. filter()
– Filter Values
Returns a new array containing only the matching elements.
let ages = [15, 22, 18, 30];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [22, 18, 30]
✅ 6. reduce()
– Reduce to a Single Value
Reduces the array to a single result (like sum or average).
let prices = [10, 20, 30];
let total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 60
✅ 7. every()
& some()
– Test Conditions
every()
returnstrue
if all elements pass the test.some()
returnstrue
if any element passes the test.
let numbers = [2, 4, 6];
console.log(numbers.every(n => n % 2 === 0)); // true
console.log(numbers.some(n => n > 5)); // true
📌 Summary Table
Method | Description | Returns |
---|---|---|
for | Traditional loop with full control | – |
forEach() | Calls a function for each item | undefined |
for...of | Iterates over array values | – |
map() | Transforms array, returns new array | New array |
filter() | Filters values, returns matching ones | New array |
reduce() | Reduces to a single value | Any value |
every() | Checks if all elements pass a test | true/false |
some() | Checks if any element passes a test | true/false |
🧠 Final Thoughts
- Use
for
orfor...of
when you need control over the loop. - Use
forEach()
for clean, simple iteration. - Use
map()
,filter()
,reduce()
for functional programming. - Use
every()
andsome()
to test conditions.