Arrays are used to store multiple values in a single variable. In most applications, we need to process each element in an array. This process is called array iteration.
What is Array Iteration?
Array iteration means going through each element of an array one by one and performing some operation on it.
const numbers = [1, 2, 3];
If you want to access each value, you iterate through the array.
Traditional Ways of Iteration
for Loop
const numbers = [1, 2, 3];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
for...of Loop
for (let num of numbers) {
console.log(num);
}
These methods work, but JavaScript provides built-in functions that make iteration easier and cleaner.
Array Iteration Methods
These are built-in methods that help you work with arrays efficiently.
forEach()
The forEach method is used to execute a function for each element in the array.
const numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num);
});
It does not return a new array.
map()
The map method is used to transform each element and return a new array.
const numbers = [1, 2, 3];
const doubled = numbers.map(function(num) {
return num * 2;
});
filter()
The filter method is used to select elements that match a condition.
const numbers = [1, 2, 3, 4];
const even = numbers.filter(function(num) {
return num % 2 === 0;
});
find()
The find method returns the first element that satisfies a condition.
const numbers = [1, 2, 3, 4];
const result = numbers.find(function(num) {
return num > 2;
});
some()
The some method checks if at least one element satisfies a condition.
const numbers = [1, 2, 3];
const hasEven = numbers.some(function(num) {
return num % 2 === 0;
});
every()
The every method checks if all elements satisfy a condition.
const numbers = [2, 4, 6];
const allEven = numbers.every(function(num) {
return num % 2 === 0;
});
reduce()
The reduce method is used to combine all elements into a single value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function(acc, curr) {
return acc + curr;
}, 0);
Key Differences
- forEach executes a function for each element and does not return a new array
- map transforms elements and returns a new array
- filter selects elements based on a condition
- find returns the first matching element
- some checks if any element matches
- every checks if all elements match
- reduce combines all elements into one value
Real-World Example
const transactions = [
{ amount: 500, type: "expense" },
{ amount: 2000, type: "income" },
{ amount: 300, type: "expense" }
];
const expenses = transactions.filter(function(t) {
return t.type === "expense";
});
const totalExpense = expenses.reduce(function(sum, t) {
return sum + t.amount;
}, 0);
Conclusion
Array iteration methods help you process data in a clean and efficient way. Instead of writing manual loops, you can use these built-in functions to make your code simpler, more readable, and easier to maintain.
Top comments (0)