The map() Method in JavaScript: A Tool for Creating New Arrays
Among JavaScript's array methods, map() is one of the most powerful. It allows iterating over all elements of an array and returning a new array where each element is derived from the original array's element with some transformation.
In this article, we will learn:
- What map is
- How it works
- What it returns
- How it differs from forEach
- How to implement map from scratch
Syntax
array.map(function(element, index, array) {
// the returned value will be an element of the new array
});
Parameters
- element – the current element
- index – the current index
- array – the entire array
Simple Example
const numbers = [1, 2, 3];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6]
The original array remains unchanged, and a new array is returned.
Difference from forEach
- forEach – used to perform an action
- map – used to create a new array of transformed values
const nums = [1, 2, 3];
const withForEach = [];
nums.forEach(n => withForEach.push(n * 2));
const withMap = nums.map(n => n * 2);
console.log(withForEach); // [2, 4, 6]
console.log(withMap); // [2, 4, 6]
Both iterate over elements, but map automatically returns a new array, making it more convenient.
Important Details
- map does not modify the original array.
- Returns a new array of the same length.
- Can be combined with other methods like filter, reduce, etc.
Real-World Example
const users = [
{ name: 'Anna', age: 25 },
{ name: 'David', age: 30 },
{ name: 'Narek', age: 22 },
];
const names = users.map(user => user.name);
console.log(names); // ['Anna', 'David', 'Narek']
How the map() Method Works Internally
Like forEach, map is a method attached to Array.prototype.
When we write:
[1, 2, 3].map(fn);
It is the same as:
Array.prototype.map.call([1, 2, 3], fn);
Let’s Write Our Own myMap() Function
function myMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i, array));
}
return result;
}
Usage:
const nums = [1, 2, 3];
const doubled = myMap(nums, function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6]
We Can Add It to Arrays (For Educational Purposes)
Array.prototype.myMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
Usage example:
const names = ['anna', 'david'].myMap(name => name.toUpperCase());
console.log(names); // ['ANNA', 'DAVID']
Reminder: Modifying built-in prototypes is not recommended in production environments.