The map() method in JavaScript
The map() method in JavaScript is a tool for creating a new array.
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:
array.map(function(element, index, array) {
// the returned value will be an element of the new array
});
Parameters
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.
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.
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']
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);
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]
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.