JavaScript Array Iteration
Arrays often contain multiple values, and you may need to access each element one by one. This process is called array iteration.
JavaScript provides different ways to iterate through arrays. Some methods are used for displaying data, while others are useful for creating a new array or filtering data.
In this article, you will learn:
- for loop
- for…of loop
- forEach()
- map()
- filter()
for Loop
The for loop is the most common way to iterate through an array.
Syntax
for (initialization; condition; increment) {
// code
}Example
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}Output
Apple
Banana
Mango
for…of Loop
The for…of loop directly accesses array values.
Syntax
for (let variable of arrayName) {
// code
}Example
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}Output
Apple
Banana
Mango
forEach()
The forEach() method executes a function once for every array element.
Syntax
arrayName.forEach(function(element) {
// code
});Parameters
- element → Current array element.
Example
let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach(function(fruit) {
console.log(fruit);
});Output
Apple
Banana
Mango
map()
The map() method creates a new array by transforming each element.
Syntax
arrayName.map(function(element) {
return value;
});Example
let numbers = [1, 2, 3];
let result = numbers.map(function(num) {
return num * 2;
});
console.log(result);Output
[2, 4, 6]
filter()
The filter() method creates a new array containing only the elements that match a condition.
Syntax
arrayName.filter(function(element) {
return condition;
});Example
let numbers = [10, 20, 30, 40];
let result = numbers.filter(function(num) {
return num > 20;
});
console.log(result);Output
[30, 40]
Method Comparison
| Method | Purpose | Returns |
| for | Loop through elements | Nothing |
| for…of | Loop through values | Nothing |
| forEach() | Execute a function for each element | undefined |
| map() | Create a new transformed array | New Array |
| filter() | Get matching elements | New Array |