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
| Method | Description |
|---|---|
| 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
1 or earlier ×
2 or earlier ×
8 or earlier ×
9 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.