Array Iterations in JavaScript

작성자

카테고리:

← 피드로
DEV Community · Pranay Rebeyro · 2026-07-21 개발(SW)

Pranay Rebeyro

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.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다