Tutorial

Introduction to Maps in JavaScript

Updated on May 26, 2022
authorauthor

Alligator.io and Kong Yang

Introduction to Maps in JavaScript

Introduction

The JavaScript programming language has evolved over time, bringing along with it many new features. A significant update was made in 2015 that changed the way developers use the language. JavaScript 2015 (ES6) introduced a feature called Map. Not to be confused with the .map() array method, the built-in Map object is another way to structure your data. Maps are collections of distinct and ordered key-value pairs.

This tutorial will introduce a few concepts that will help you understand and create a new Map object for your JavaScript application.

Prerequisites

To follow along with this tutorial, you should have a general understanding of JavaScript and the Object data type. You can learn more about JavaScript from our JavaScript tutorial series and about JavaScript Objects specifically in this tutorial.

You should also be able to use the JavaScript Developer Console in your web browser or your favorite text editor to execute the JavaScript code examples. The examples in this tutorial use the Chrome JavaScript console to execute the code. You can use whichever tool you prefer.

Creating a New Map

Begin by opening your text editor or the JavaScript console in your web browser. Create a new Map object by initializing a variable called items with the value new Map():

let items = new Map();

The items variable you created holds an empty Map object. You can observe the contents of the items variable in the console by typing:

items;
Output
Map(0) {size: 0}

Notice that the output reveals the size of the Map object as 0. There are methods on the Map object that you can use to update it. There are also properties on the Map object that you can use to glean information about your Map.

Using Map Methods

The Map object includes methods that you can use to manipulate your key-value pairs.

.set() Method

You can fill your empty Map object with the .set() method. The .set() method takes in two parameters: a key that you can use to identify an item with and the value of the item. Unlike an object literal, the key and value pair can be any data type.

This is the syntax to fill a Map object with key-value pairs using the .set() method:

your_data.set(key, value);

For example, to fill in your items Map object with some new key-value pairs, append the items variable with the following lines in your console:

items.set('item-1','Car');
items.set('item-2', 'Lawn Mower');
items.set('item-3', 'Bicycle');
items.set('item-4', 'Rake');

You can also chain together key-value pairs like this:

items.set('item-1', 'Car')
      .set('item-2', 'Lawn Mower')
      .set('item-3', 'Bicycle')
      .set('item-4','Rake');

After filling your items Map object with some key-value pairs, you can double check to see if it was filled correctly by typing it in the console. This will return the entire items Map object to you:

items;
Output
Map(4) {'item-1' => 'Car', 'item-2' => 'Lawn Mower', 'item-3' => 'Bicycle', 'item-4' => 'Rake'}

.get() Method

To retrieve a value from the Map object, use the .get() method. You have to know the key in order to retrieve a value.

Retrieve a value from the items Map object by appending the .get() method with a known key:

items.get('item-1');
Output
'Car'

If you enter an invalid key or if the key you’re searching for can’t be found, this method will return undefined:

items.get('item-5');
Output
undefined

.has() Method

You can search within your Map object to determine if a specific key exists with the .has() method:

items.has('item-4');
Output
true

The output is a boolean. It returns true if the key is found in the Map object and false if it isn’t:

items.has('item-10');
Output
false

.delete() Method

You can remove an item from the Map object using the .delete() method:

items.delete('item-2');
Output
true

The output returns true for a successful removal of the item. It will return false if an item with the specified key is not found in the Map object.

.clear() Method

You can remove all the items from your Map object by using the .clear() method:

items.clear();
Output
undefined

The return value of undefined is expected. After using the .clear() method, if you type in your items Map object into the console, you’ll notice that it no longer contains any entries:

items;
Output
Map(0) {size: 0}

Using the .size Map Property

If you want to know the current size of a Map object, you can use the .size property to output how many entries it contains:

items.size;
Output
0

Notice that there isn’t a () after .size. This is because .size is not a method, but a property that you can access on the Map object to gather information from. It may be helpful to use the .size property when you aren’t sure how many entries you’re working with in a particular dataset.

Initializing a Map from an Array

You may encounter datasets with multi-dimensional arrays which are arrays within an array. If the inner array has exactly two values, you can use the first value in that array as the key identifier, and the second array value as the Map value.

To demonstrate this, enter the following lines into your console or text editor:

const food = [
  ['food-item-1', 'Pizza'],
  ['food-item-2', 'Burger'],
  ['food-item-3', 'Taco'],
];

let menu = new Map(food);

menu.get('food-item-2');
Output
'Burger'

In this example, the multi-dimensional array contains within it arrays with two different values. The first value of food-item-1 is being used as the key, and the second value in the array of Pizza as the value for your new Map object.

You’ll notice that when you’re creating a new Map object from an array, you pass in the array as an argument.

Note: It’s important to understand that when you’re creating a new Map object, you’re not changing the original array. You’re creating a copy of the original array into your new Map object. Any changes that you make to your new Map object will not affect the original array.

Once you’ve created a copy of the array, you can use Map methods, like .get(), to change and edit your Map object.

Iterating Over the Map Object

You can iterate over your Map object by using loops like for…of.

Create a new activities Map object and set it with four different key-value pairs. You can then use a for...of loop to iterate over the Map object items:

let activities = new Map();

activities.set(1, 'Snowboarding');
activities.set(2, 'Car Racing');
activities.set(3, 'Canoeing');
activities.set(4, 'Tennis');

for (let [number, activity] of activities) {
  console.log(`Activity ${number} is ${activity}`);
}
Output
Activity 1 is Snowboarding Activity 2 is Car Racing Activity 3 is Canoeing Activity 4 is Tennis

You can also use the .forEach() method to iterate over a Map in the same manner.

Note: Notice how the first argument in the forEach() callback function is the value and the second is the key. You can learn more about this syntax structure on Mozilla’s helpful MDN reference site.

The following will have the same result as the for...of example:

activities.forEach((value, key) => {
  console.log(`Activity ${key} is ${value}`);
});
Output
Activity 1 is Snowboarding Activity 2 is Car Racing Activity 3 is Canoeing Activity 4 is Tennis

Conclusion

In this tutorial, you created a new Map object and learned about the different methods to update it. You can continue to explore our How to Code in JavaScript series to learn more about the inner workings of JavaScript.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alligator.io

author


Default avatar
Kong Yang

author


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.