How to Use Map in JavaScript

Danielle Richardson Ellis
Danielle Richardson Ellis

Published:

Sometimes, figuring out the most effective data structures or functions to use in your code can get very complex, very quickly. Simplifying your codebase can save you a lot of time, enhance your code’s readability, and increase its overall performance.

Software Engineer pointing to the computer screen to show another Software Engineer how to use the map function in JavaScript.

One way to simplify your code is using map() in JavaScript. Map is a powerful tool we can use to make changes to all the elements of a JavaScript array, rather than making those changes through JavaScript objects. Thanks to the new ES6 update and its introduction to some amazing new syntax and features such as map(), we now have more modern and readable code.

We will cover what the map function does in JavaScript, how to work with it, and discuss some of its properties and methods. Let’s get started.Download Now: An Introduction to JavaScript  [Free Guide]

What does the Map function do in JavaScript?

Before we introduce the map() function and how it is used, let’s jump right into defining it.

What is a Map in JavaScript?

Map is a collection of key/value pairs that can use any type of data as a key or value and remember the order of its entries. It is used to iterate over all the elements in an array, which results in a new array. In other words, you can take an array, make changes to the elements, and get a new array based on what is returned by the function. This is why map is useful for fast searching and looking up data.

Before the introduction of map, you would have to use an object. The problem with using an object is that it limits keys to only strings or integers.

Map, on the other hand, allows keys to be anything such as arrays, objects, numbers, etc.

The most significant improvement of the map feature is the ability to iterate through the data structures in the order that the objects were added. Like objects, you can add/delete new and existing keys and retrieve their value while using map. We will discuss how to do this in more detail later.

How to Use Map in JavaScript

Map can be used when you want to perform an action on each element in a collection, and gather the results into a new array. In JavaScript, the "for loop" or "nesting" can complete the same task, but we can use map() to create more readable functions.

Map can be created and initialized with the new Map() syntax. You have the option of assigning it a value later.

In this example, we created a new Map called myMap. When the code is run it will output an empty map. See below:

 let myMap = new Map()
// Output:
// => Map(0) {}

You can also use new Map() to create a new Map object by passing in an array. We will create a new Map object that stores some popular songs as the key and the artist’s name as the value. See the output below:

 let playlist = new Map([["Shake it Off", "Taylor Swift"], ["Umbrella", "Rihanna"], ["Uptown Funk", "Bruno Mars"]]);

console.log(playlist);
//Output:
// Map {"Shake it Off" => "Taylor Swift", "Umbrella" => "Rihanna", "Uptown Funk" => "Bruno Mars"}

Next, let’s discuss more efficient ways of adding/removing elements into the map method, along with other properties and methods.

Map Properties and Methodsjs-map-table

Pulling from this list, we will go into detail with a few of these properties.

Adding Elements to a Map

To add new key/value pairs to the map, use the set() method.

 playlist.set("Firework", "Katy Perry");

If you need to add more than one element, you can chain them by doing the following:

 playlist.set("Firework", "Katy Perry"); 
.set("Single Ladies", "Beyonce");

Getting the Number of Elements in the Map

The size() method returns the number of entries in the map.

 console.log(playlist.size);
// Output:
// 5

Getting Elements From a Map

If you want to see the artist of the song "Umbrella", you can use the get() method.

 playlist.get("Umbrella"); 
// Output:
// Rihanna

Removing Elements From a Map

The delete() method removes an entry in the map.

 playlist.delete("Firework", "Katy Perry");

To delete all the entries in map, use the clear() method:

 playlist.clear();

Now that you are familiar with some of the properties and methods, feel free to test them out for yourself.

Implementing Map in JavaScript

Now, we will discuss ways you can apply the map function to your code. First, let’s review the syntax.

JavaScript Map Function Syntax

The JavaScript map function syntax is as follows:

 let newArray = oldArray.map(function(currentValue, index, array) {
}, thisValue);

The same syntax can also be written using the arrow function for short:

 let newArray = oldArray.map((currentValue, index, array) => {
}, thisValue);

Description

  • newArray - This is the new array that is returned after the function is applied.
  • oldArray - This is the original array that the function will operate on.
  • thisValue - This is the value used as the function’s this value when it’s executed.

The map function will have three arguments available to it and will be called for each element in the original array:

  • currentValue - This is the value of the current element.
  • index - (optional) This is the index of the current value. We can make some changes based on the position in the array.
  • array - (optional) This is the parameter that points to the original array.

Map Function Example

Now that we’ve learned the syntax, let’s look at an example implementation of the map() function:

 let artists = ["Beyonce", "Bruno Mars", "Taylor Swift"];

let bestArtist = artists.map(function(artist) {
return artist + "the best"
});

console.log(bestArtist);
//Output:
// ["Beyonce the best", "Bruno Mars the best", "Taylor Swift the best"];

Note: The original map array (artists) doesn’t change.

Executing Map in JavaScript

In this post, you have learned a lot about implementing the map method with JavaScript as well as the difference between using a map and an object. Using an object is beneficial when you only need a simple structure to store data that are strings, integers, or symbols. Map is good to use with large sets of data or when the keys are unknown.

With this useful concept, you are a step closer to building a more modern and readable application. Consider applying map in place of the standard object in your next coding venture.

New Call-to-action

Topics: Javascript

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about one of the world's most popular programming languages.