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

MethodPurposeReturns
forLoop through elementsNothing
for…ofLoop through valuesNothing
forEach()Execute a function for each elementundefined
map()Create a new transformed arrayNew Array
filter()Get matching elementsNew Array

✅Follow us for more updates:

Follow on LinkedIn Join WhatsApp Channel

JavaScript

Scroll to Top