Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. Array .forEach() / map()

Array .forEach() / map() Since: ES5(ECMAScript 2009)

A method that executes a function once for each element in an array. map() creates a new array from the return values of the function.

Syntax

// Executes a function for each element in an array.
arr.forEach(function(element, index, arr) {
	// process
});

// Transforms each element and creates a new array.
var newArray = arr.map(function(element, index, arr) {
	return transformedValue;
});

Method List

MethodDescription
forEach(function)Executes a function once for each element in the array. Returns no value. The loop cannot be stopped partway through.
map(function)Executes a function for each element in the array and returns a new array built from the return values. The original array is not modified.

Sample Code

var numbers = [1, 2, 3, 4, 5];

// Print each element using forEach.
numbers.forEach(function(num, index) {
	console.log(index + ": " + num);
});

// Use map to create a new array with each element doubled.
var doubled = numbers.map(function(num) {
	return num * 2;
});
console.log(doubled); // Outputs "2,4,6,8,10".
console.log(numbers); // Outputs "1,2,3,4,5". The original array is unchanged.

// Use map to convert elements to strings.
var labels = numbers.map(function(num) {
	return "No." + num;
});
console.log(labels); // Outputs "No.1,No.2,No.3,No.4,No.5".

Overview

Both array.forEach() and array.map() execute a function for each element in an array, but they serve different purposes. array.forEach() is used simply to loop through elements and returns no value. array.map(), on the other hand, transforms each element to build a new array and does not modify the original array.

The callback function receives three arguments: the first is the value of the current element, the second is its index, and the third is the array itself. The second and third arguments are optional and can be omitted if not needed.

Unlike a for loop, array.forEach() provides no way to stop the loop early. The break statement cannot be used, and a return statement only skips the current iteration. If you need to stop when a condition is met, use a for loop or consider using array.some().

Browser Compatibility

Chrome Chrome
49+
Supported in all versions
Firefox Firefox
57+
1 or earlier ×
Safari Safari
18+
2 or earlier ×
Edge Edge
80+
11 or earlier ×
IE IE
11+
8 or earlier ×
Opera Opera
48+
9 or earlier ×
iOS Safari iOS Safari
18+
Supported in all versions
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .