Array iteration is a fundamental concept in JavaScript, allowing developers to manipulate or analyze array elements. JavaScript provides multiple methods to iterate through arrays efficiently.
Basics of Array Iteration
Array iteration involves looping through each element in an array to perform a specific task, such as printing, modifying or aggregating data. JavaScript offers a variety of tools for array iteration, including traditional loops and modern methods like forEach and map.
Iteration Methods
1. Traditional for Loop
The for
loop is one of the oldest and most flexible ways to iterate over an array.
Syntax:
for (let i = 0; i < array.length; i++) {
// Code to execute for each element
}
Example:
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]); // Output: 1 2 3 4 5
}
2. for…of Loop
The for…of loop simplifies iteration by directly accessing array elements.
Syntax:
for (const element of array) {
// Code to execute for each element
}
Example:
let fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
console.log(fruit); // Output: Apple Banana Cherry
}
3. forEach() Method
The forEach() method executes a callback function for each array element.
Syntax:
array.forEach((element, index, array) => {
// Code to execute for each element
});
Example:
let colors = ["Red", "Green", "Blue"];
colors.forEach((color, index) => {
console.log(`Index: ${index}, Color: ${color}`);
});
// Output:
// Index: 0, Color: Red
// Index: 1, Color: Green
// Index: 2, Color: Blue
4. map() Method
The map() method creates a new array by applying a function to each element of the original array.
Syntax:
let newArray = array.map((element, index, array) => {
// Return modified element
});
Example:
let numbers = [1, 2, 3];
let squared = numbers.map((num) => num * num);
console.log(squared); // Output: [1, 4, 9]
5. filter() Method
Although primarily used for filtering elements, filter() can also be part of iteration tasks.
Example:
let numbers = [10, 15, 20, 25];
let filtered = numbers.filter((num) => num > 15);
console.log(filtered); // Output: [20, 25]
6. reduce() Method
The reduce() method accumulates array values into a single output based on a callback function.
Syntax:
let result = array.reduce((accumulator, currentValue, index, array) => {
// Return accumulated value
}, initialValue);
Example:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 10
7. every() and some() Methods
- every() checks if all elements satisfy a condition.
- some() checks if at least one element satisfies a condition.
Example:
let numbers = [10, 20, 30];
console.log(numbers.every((num) => num > 5)); // Output: true
console.log(numbers.some((num) => num > 25)); // Output: true
8. Using entries(), keys() and values()
These methods return iterators for traversing arrays.
Example:
let fruits = ["Apple", "Banana", "Cherry"];
for (const [index, value] of fruits.entries()) {
console.log(`Index: ${index}, Value: ${value}`);
}
// Output:
// Index: 0, Value: Apple
// Index: 1, Value: Banana
// Index: 2, Value: Cherry
Choosing the Right Iteration Method
Scenario | Preferred Method |
---|---|
Simple tasks | for or for…of |
Applying a function to elements | map() |
Filtering elements | filter() |
Aggregating data | reduce() |
Checking conditions | every() or some() |
Iterating with indices | forEach() or entries() |
Practical Applications
- Calculating Totals:
let prices = [100, 200, 300];
let total = prices.reduce((sum, price) => sum + price, 0);
console.log(`Total: ${total}`); // Output: Total: 600
- Transforming Data:
let names = ["john", "jane", "doe"];
let capitalized = names.map((name) => name.toUpperCase());
console.log(capitalized); // Output: ["JOHN", "JANE", "DOE"]
- Filtering Data:
let ages = [12, 18, 25, 14];
let adults = ages.filter((age) => age >= 18);
console.log(adults); // Output: [18, 25]