What Is Array Iteration?
Array iteration means going through the elements of an array one by one to perform an operation.
For example, if we have a list of fruits, we can use array iteration to display each fruit without writing separate code for every item.
Let's look at some common ways to iterate through arrays in JavaScript.
1. Using a for Loop
A for loop allows us to access array elements using their index.
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
Apple
Banana
Mango
Here, i starts at 0 and increases until it reaches the array's length. We use fruits[i] to access each element.
2. Using for...of
The for...of loop lets us access each value directly without using an index.
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
This prints each fruit on a separate line.
It is a simple and readable way to iterate through array values.
3. Using forEach()
The forEach() method executes a function for every element in an array.
let numbers = [10, 20, 30];
numbers.forEach(function(number) {
console.log(number);
});
Here, the function runs once for each number in the array.
We can also write it using an arrow function:
numbers.forEach(number => console.log(number));
4. Using map()
The map() method creates a new array by transforming each element.
let numbers = [1, 2, 3];
let doubled = numbers.map(number => number * 2);
console.log(doubled);
Output:
[2, 4, 6]
Here, every number is multiplied by two, and the results are stored in a new array.
5. Using filter()
The filter() method creates a new array containing only the elements that satisfy a condition.
let numbers = [10, 15, 20, 25, 30];
let result = numbers.filter(number => number > 20);
console.log(result);
Output:
[25, 30]
Here, only numbers greater than 20 are included in the new array.
Difference Between These Methods
- for loop: Useful when we need control over the index and loop execution.
- for...of: Useful when we want to access each array value directly.
- forEach(): Useful when we want to perform an action for each element.
- map(): Useful when we want to transform elements and create a new array.
- filter(): Useful when we want to select elements that match a condition.
Why Is Array Iteration Important?
Array iteration is useful when working with:
- Lists of products in an online store.
- Student marks and records.
- Data received from APIs.
- Filtering and displaying information.
- Calculating totals and processing collections of values.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.