A Deep Dive into the Javascript map() Method

Adam Drake
5 min readJan 15, 2024

--

The map()method in Javascript is a super useful Array method to add to your JS toolbelt. In fact it’s pretty hard to do much in JS these days without some exposure to the map() method. It’s a very widely used method.

However, I have always been curious how it works under the hood so this is what I want to explore in this article. The first part of the article will explain what the map() method is and some cool uses of it. The second part will dig below the surface and find out how it is actually implemented.

What is the map() method

According to the MDN documentation on the map() method, the map() method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array.

Pretty straightforward. It’s basically used to do transformations on elements in an existing array and provides a new array back. The fact it creates a new array is very useful as it does not mutate the original array.

map(callbackFn)

This callbackFn is a function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:

element — The current element being processed in the array.

index — The index of the current element being processed in the array.

array — The array map() was called upon.

(We’ll look at an example witht the array argument a bit later…)

Simple Example of the map() method

Let’s look at a super simple example so you get the idea of what a map() method does and what it doesn’t do.

// Suppose we have an array of numbers
const numbers = [1, 2, 3, 4, 5];

// Using map() to square each number in the array
const squaredNumbers = numbers.map(function (number) {
return number * number;
});

// The new array will contain the squared values
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

So in this example we have an array — numbers This numbers array is mapped over using the map() method and each element is multiplied by itself. This squared value is then placed into a new array. So when every element has gone through this map method we are returned a new array squaredNumbers.

Example of map() method using the index argument

Next is an example using the second argument — index of the map() method.

const fruits = ['apple', 'banana', 'cherry'];

// Using map() with the index
const fruitWithIndex = fruits.map(function (fruit, index) {
return `${fruit} is at index ${index}`;
});

console.log(fruitWithIndex);
// Output: ["apple is at index 0", "banana is at index 1", "cherry is at index 2"]

In this example we can see that we are mapping over a fruits array. For each element we are returning a string with the fruit name and then we are also printing out the index. Remember! Array indexes (indices?!) start at 0.

Example of map() method using the array argument

Finally is an example of the map array being used with all three potential arguments — element, index, array.

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

// Using map() with all three arguments
const transformedArray = numbers.map(function (element, index, array) {
return `Element: ${element}, Index: ${index}, Array: [${array}]`;
});

console.log(transformedArray);
// Output:
// ["Element: 1, Index: 0, Array: [1,2,3,4,5]",
// "Element: 2, Index: 1, Array: [1,2,3,4,5]",
// "Element: 3, Index: 2, Array: [1,2,3,4,5]",
// "Element: 4, Index: 3, Array: [1,2,3,4,5]",
// "Element: 5, Index: 4, Array: [1,2,3,4,5]"]

I admit it’s not the most imaginative example in the world but it does illustrate the point that you have access to all these three arguments inside the map() method.

Example of map() method used in React

A very common place where the map() method is used nowadays is to help map over some data (from an api or some local source) and then render out some UI (React Components).

import React from 'react';

const UserList = () => {
const users = [
{ id: 1, firstName: 'John', lastName: 'Doe' },
{ id: 2, firstName: 'Jane', lastName: 'Smith' },
{ id: 3, firstName: 'Alice', lastName: 'Johnson' },
];

return (
<div>
<h1>User List</h1>
<ul>
{/* Using map() to render a list of users */}
{users.map(user => (
<li key={user.id}> // Adding the key is very important for React!
{`${user.firstName} ${user.lastName}`}
</li>
))}
</ul>
</div>
);
};

export default UserList;

In this example we have an array of users and in the React Component we are using the map() method to map over this array and then render our the user’s firstName and lastName as a list item.

Helpful Tip with the map() method

When undefined or nothing is returned, the resulting array contains undefined. If you want to delete the element instead, chain a filter() method, or use the flatMap() method and return an empty array to signify deletion.

How map() method works under the hood

I am always interested in how things work and this curiosity is what led me to programming in the first place. So whenever I learn something like this I am always curious what is going on underneath the surface level.

For the map() method it isn’t actually anything too complicated. It’s basically this:

function map(array,callback){
let newArray=[];
for (let i=0; i<array.length; i++){
newArray.push(callback(array[i]))
};
return newArray
}

You pass the map() method the original array and the callback function within the map() method. The function creates a new array. Then uses a for loop to iterate over the existing array, call the callback on each item of that exisiting array and then push it to the new array. Then the function returns this new array. Neat!

map() method type definition

This is the type definition for the map() method when you go to it’s definition in a code editor:

 /**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

Conclusion

The map() method is a must have for any develop who wants to say they develop in Javascript/Typescript. It’s a simple method but a very useful one and one you will be finding yourself using plenty to help you manipulate data.

About me

I am a Frontend Developer working mainly with React and Typescript in my day to day professional life. I love exploring new tools and libraries and love the Javascript Ecosystem.

I like to write blog posts that share exciting new tools I’ve discovered, how-to articles and also the occasional opinion piece.

I live in Prague in the Czech Republic with my family.

Check out the original blog post on my blog.

--

--

Adam Drake

I'm a Frontend Developer and I write about all things Frontend Related - Think lightly of yourself and deeply of the world. Based in Prague, CZ