DEV Community

Pranay Rebeyro
Pranay Rebeyro

Posted on

Array Iterations in JavaScript

forEach()
The forEach() method executes a function once for each element in an array.

It is mainly used when you want to perform an action, such as printing values, updating the UI, or making API calls.

array.forEach(function(element, index, array) {
    // code
});
element  Current array element
index  Position of the current element
array  Original array
Enter fullscreen mode Exit fullscreen mode

Example 1: Print All Elements

let fruits = ["Apple", "Mango", "Orange"];

fruits.forEach(function(fruit) {
    console.log(fruit);
}); // Output:
Apple
Mango
Orange
Enter fullscreen mode Exit fullscreen mode

Example 2: Using Index

let fruits = ["Apple", "Mango", "Orange"];

fruits.forEach(function(fruit, index) {
    console.log(index + " : " + fruit);
}); // Output:
0 : Apple
1 : Mango
2 : Orange
Enter fullscreen mode Exit fullscreen mode

forEach() does not return a new array.

let numbers = [1, 2, 3];

let result = numbers.forEach(num => num * 2);

console.log(result); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

map()
The map() method creates a new array by applying a function to every element of the original array.

It is mainly used when you want to modify or transform array elements.

array.map(function(element, index, array) {
    return newValue;
});
element  Current array element
index  Position of the current element
array  Original array
Enter fullscreen mode Exit fullscreen mode

Example 1: Double Every Number

let numbers = [1, 2, 3, 4];

let doubled = numbers.map(functio
n(num) {
    return num * 2;
});

console.log(doubled); // Output:
[2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Original Array vs New Array

let numbers = [1, 2, 3];

let doubled = numbers.map(num => num * 2);

console.log(numbers);
console.log(doubled); // Output:
[1, 2, 3]
[2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Notice that map() does not change the original array. Instead, it returns a new array.

Top comments (0)