You can use the .get(key)
method to retrieve a value from a Map
.
Example:
let myMap = new Map();
myMap.set('name', 'John');
console.log(myMap.get('name')); // Output: John
Key takeaways:
A map provides a robust way to store and retrieve key-value pairs. It addresses objects’ limitations, such as inconsistent iteration and key collision issues. It allows any type of key and remembers the order of insertion.
A set ensures all stored elements are unique, making it ideal for handling collections where duplicates must be avoided. It offers straightforward methods to add, remove, and check the presence of elements.
Map and set simplify complex operations such as managing unique collections, filtering data, or working with key-value pairs, providing a more elegant and error-free approach than earlier JavaScript practices.
Tired of awkward workarounds to manage unique data or key-value pairs in JavaScript?
Before ES6, removing duplicates or using objects as makeshift maps was messy and error-prone. But with Map and Set, JavaScript now offers efficient, elegant ways to handle data.
JS Assessment: Assess your Javascript skills
Test your Javascript skills by trying out exercises in your browser. These exercises were originally created by Rebecca Murphy and released under "js-assessment". By doing these exercises, you will learn about Javascript Arrays, Strings, Functions, Objects, Inheritance, Regular Expressions etc.
In this tutorial, you’ll learn how to leverage Map and Set to write cleaner, faster, and more maintainable code. Plus, we’ll dive into hands-on challenges to solidify your learning.
While other programming languages provided lists, sets, associative maps, and dictionaries, JavaScript primarily relied on arrays and objects. This meant:
No built-in way to store unique values.
Objects are being used as makeshift maps, leading to unexpected behavior.
Performance issues when handling large datasets.
With ES6, JavaScript introduced map
and set
, two powerful built-in classes designed for efficient data storage and retrieval. These modern structures bring:
The set
is used for handling unique values without extra logic.
The map
is used for optimized key-value storage with better performance than objects.
Try this quick challenge!
Before diving in, can you guess the output of this JavaScript snippet?
const set = new Set([1, 2, 2, 3, 4]);console.log(set.size); // What do you think?const map = new Map();map.set('apple', 5);map.set('apple', 10);console.log(map.get('apple')); // What's the final value?
Run it and see if your guess was right! If you’re surprised, you’re about to learn how a map and set simplify JavaScript programming while making your code cleaner and more efficient.
Let’s dive in and modernize your JavaScript skills!
If you get stuck, that’s okay. We have plenty of courses in Educative that can help you get a start on everything.
A JavaScript map is an ordered collection of key-value pairs where the keys and values can be of any data type. Unlike JavaScript objects, which are traditionally used for key-value storage but have several limitations, the map provides optimized key-value storage and retrieval with built-in methods that make working with data more efficient.
Maintains the order of insertion
When you add key-value pairs to a map, it remembers the original insertion order.
This is unlike objects, where the order of keys isn’t guaranteed.
Allows any data type as keys
Objects in JavaScript only allow strings or symbols as keys.
A map can have numbers, objects, functions, or even another Map as keys.
Improved performance for frequent additions and lookups
The map is optimized for large-scale data storage and retrieval, performing faster than objects in most cases, especially when keys are not simple strings.
Has built-in iteration methods
Unlike objects, which require Object.keys()
, Object.values()
, or Object.entries()
to iterate, Map
provides direct methods for iteration (keys()
, values()
, entries()
).
While objects and maps are both used for storing key-value pairs, they function differently.
Feature | Objects | Map |
Key types | Strings and symbols only | Any data type (objects, numbers, etc.) |
Order | Not guaranteed | Preserves insertion order |
Performance | Slower for frequent operations | Optimized for frequent additions/lookups |
Iteration | Requires manual conversion ( | Built-in iterators ( |
Size | Manually count |
|
Serialization | Limited support with JSON | Not directly supported |
Let’s have a look at how we can implement it. To create a new map, we use the following syntax:
let map = new Map([iterable]);
Let’s apply this to a more complex example. Below is a map that holds names as keys and scores as values.
'use strict';//START:DEFINEconst scores =new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);scores.set('Jake', 14);console.log(scores.size);//END:DEFINE
scores
map has been initialized with names and scores. The initial data may be any iterable with a pair of keys and values.set()
method (line 7)Note:
Map.has(key)
above will return the boolean value to indicate if the element associated with a specified key is in the map.
Once we understand how to create maps in JavaScript, we can leverage their powerful features for efficient data management.
One of the key operations when working with maps is iteration. JavaScript provides three built-in methods for iterating over a map object:
map.keys()
: Returns an iterable for keys.map.entries()
: Returns an iterable for entries [key, value]
.map.values()
: Returns an iterable for values.We can iterate over the collection of keys and values with the entries()
method, which returns an iterable so that we can use the enhanced for
loop along with destructuring.
For example, below, we extract the name and score for each key-value pair:
'use strict';//START:DEFINEconst scores =new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);scores.set('Jake', 14);//END:DEFINEfor(const [name, score] of scores.entries()) {console.log(`${name} : ${score}`);}
We can also use the forEach
method, which is an internal iterator.
'use strict';//START:DEFINEconst scores =new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);scores.set('Jake', 14);//END:DEFINEscores.forEach((score, name) => console.log(`${name} : ${score}`));
The first parameter that the function receives is the value for a key that appears as the second parameter. The same forEach
method can be used to iterate over only the values:
'use strict';//START:DEFINEconst scores =new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);scores.set('Jake', 14);//END:DEFINEscores.forEach(score => console.log(score));
If you receive only one parameter, it will be the value, and if you receive two parameters, then it will stand for the value and key for each key-value pair.
You can also pass an iterable object to the Map()
constructor:
let userRoles = new Map([['sarah', 'admin'],['bob', 'editor'],['jill', 'subscriber']]);
We can get elements from a map by key with the get()
method:
userRoles.get('sarah'); // admin
But if you pass a key not in that map, it will return undefined.
let foo = {name: 'Foo'};
userRoles.get(foo); //undefined
We can use the size
property to get the number of elements in our maps.
console.log(userRoles.size); // 3
Sometimes, you may want to work with an array instead of an iterable object. We can use the spread operator to convert keys for each element into a new array.
var keys = [...userRoles.keys()];
console.log(keys);
This piece of code will convert the values of elements to an array:
var roles = [...userRoles.values()];
console.log(roles);
clear()
: Removes elements from the map object.map.set(key, value)
: Stores the value by the key.delete(key)
: Removes a specific element (as specified by the key).set(key, value)
: Sets the value for the key and returns the map object. It can be chained with other methods.
*ma p.size
: Returns the current element count.To solidify your learning, let’s do a hands-on exercise with a map in JavaScript. Use a map to get the desired output as given below. Creating an object of createTodo()
should return a map element.
Input call | Expected Output |
|
|
|
|
|
|
|
|
The solution to this challenge is given below. Try it yourself first.
'use strict';const createTodo = function() {const todo = new Map();//Add your code herereturn todo;};const completedCount = function(map) {//Add your code herereturn;};const todo = createTodo(); //Returns a Map
Start by creating a map element. The map object todo
is created on line 4 using the built-in class. You can see that the map object, todo
is calling Map.get()
with different keys to get their values. This means that we need to add all the keys and values.
We add the new element in todo
with the keys and associated values. On lines 5-7, we add the new elements by setting values for the keys.
For completedCount()
, we define a new function with a map object parameter. The function will return the count of tasks that are completed. So, essentially, we are filtering all the values of elements in the map object to get the elements with the value equal to done
(see line 14).
Line 15 uses the length property to get the count of the special elements.
Let’s move toward the discussion of the set and what it offers.
A set is a collection introduced in ES6 that stores unique values of any data type. Unlike arrays, which allow duplicate values, a set ensures that each value appears only once, making it ideal for handling unique collections efficiently.
Guarantees unique values
A set automatically removes duplicates, ensuring that all stored values are distinct.
This eliminates the need for additional logic to filter out duplicates from arrays.
Supports any data type
A set
can store numbers, strings, objects, and functions like a map.
It maintains a strict reference-based comparison, meaning { id: 1 } !== { id: 1 }
.
Maintains order of insertion
Unlike regular objects, which don’t guarantee key order, a set preserves the sequence of added elements.
Built-in iteration methods
The set provides methods like values()
, keys()
, and entries()
, making it easy to iterate without needing extra conversions like Object.keys()
.
While both arrays and sets can store collections of data, they work differently:
Feature | Arrays | Sets |
Duplicates | Allows duplicates | Stores unique values |
Insertion Order | Preserved | Preserved |
Index-Based Access | Yes (via arr[index]) | No direct index access |
Lookup Performance | Slower (O(n)) | Faster (O(1)) |
Iteration Methods |
|
|
Conversion | Requires Set() for uniqueness | It can be converted to an array using the spread operator |
Let’s explore this with an example. Below, we have a set of names with five values. One value is not included in the set due to duplication.
'use strict';//START:CREATEconst names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);//END:CREATE//START:SIZEconsole.log(names.size);//END:SIZE
We can add elements to an existing set, like below:
names.add('Matt');
The add()
method returns the current set, which is useful for chain operations, such as more calls to add()
or other methods of set:
names.add('Kate').add('Kara');
Let’s execute the code below to see the chain operation in action.
'use strict';//START:CREATEconst names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);//END:CREATE//START:ADDnames.add('Mike');//END:ADD//START:ADD2names.add('Kate').add('Kara');//END:ADD2console.log(names.has('Brad'));console.log(names.entries());console.log(names.keys());console.log(names.values());//START:ITERATE1for(const name of names) {console.log(name);}//END:ITERATE1
Set does not yet offer methods like filter()
and map()
, but we can create an array from the set and use a functional style methods on that new array.
For example, below we use methods filter()
, map()
, and forEach()
to pick only names that start with J
and then transform them to uppercase.
'use strict';//START:CREATEconst names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);//END:CREATE//START:ADDnames.add('Mike');//END:ADD//START:ADD2names.add('Kate').add('Kara');//END:ADD2//START:FILTER[...names].filter(name => name.startsWith('J')).map(name => name.toUpperCase()).forEach(name => console.log(name));//END:FILTER
Use the size
property of the Set object to return its size.
const names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);
let size = names.size;
console.log(size); // 4
Use the delete()
method to remove an element from a set.
names.delete('Sara');
console.log(names); // Set(3) { 'Jack', 'Jill', 'Jake' }
And to delete all elements of a set, use the clear()
method:
names.clear();
console.log(names); // Set(0) {}
To invoke a callback on every element of your set, use the forEach()
method.
names.forEach(name => console.log(name.toUpperCase()));
new Set(iterable)
: Creates a set.set.add(value)
: Adds a given value and returns the set.set.has(value)
: Returns true
if a value exists in the set; otherwise, returns false
.set.clear()
: Removes everything from a set.To solidify your understanding of the set in JavaScript, complete this hands-on exercise. Create a set and add the following fruits to it:
apple
orange
grapes
Use a set to achieve the desired output below.
Input call | Expected Output |
|
|
|
|
|
|
|
|
The solution is provided below, but try implementing it yourself first.
'use strict';// Function to create and return a Setconst createSet = function() {const set = new Set();//Add your code herereturn set;};
Start by creating a set element. On line 4, a set object, set, is created using the built-in Set
class. A set is a collection of unique values, which makes it ideal for this use case. The task involves adding elements, checking their existence, and manipulating the size of the set.
On lines 5–7, elements are added to the set using the add method, which ensures that duplicate entries are not allowed: 'apple'
is added first, followed by 'orange'
and 'grape'
.
At this point, the set contains three elements: 'apple'
, 'orange'
, and 'grape'
. The has method checks if a specific value exists in the set. For example, on line 11, set.has('apple')
returns true because 'apple'
is present, whereas set.has('banana')
returns false because 'banana'
is not in the set.
The size property of the set object determines its current number of elements. On line 13, set.size
returns 3 since the set contains three elements.
The delete method removes an element from the set, such as on line 14 where set.delete('orange')
removes 'orange'
. After deletion, the size property is used again to confirm that the set size is 2.
When working with JavaScript’s map and set, choosing the right tool for the job can streamline your code and boost performance. Here’s a closer look at when to use each:
Use a map to store key-value pairs where the keys can be of any type, not just strings. Maps maintain the order of insertion, which is particularly useful if you plan to iterate over your data in a predictable sequence. They excel in scenarios requiring dynamic updates, quick lookups, and when keys need to be objects or other non-primitive values.
Opt for a set when your primary concern is managing a collection of unique values. Sets are designed for rapid membership checking and automatically discard duplicate entries. This makes them ideal for tasks like filtering out duplicate items from an array or maintaining a list of unique identifiers.
Data caching: Implement a caching mechanism using a map to store complex key-value pairs (e.g., caching API responses where the request parameters serve as keys). A map’s ordered structure can help implement features like the least recently used (LRU) caching.
Eliminating duplicates: Use a set to quickly remove duplicates from a dataset. For example, when processing user inputs, a set can ensure each entry is unique without additional overhead.
Configuration management: Store application settings or configuration options in a map. This approach is particularly beneficial when your configuration keys are not strictly strings and require more flexibility.
Efficient data lookup: Combine maps and sets for enhanced data processing. For example, while iterating through a large dataset, use a set to track seen elements (ensuring uniqueness) and a map to count occurrences or store related metadata.
By understanding these common use cases, you can leverage Maps and Sets to write cleaner, more efficient code tailored to your application’s needs.
In conclusion, ES6 introduced both map and set as powerful additions to JavaScript, providing robust solutions for working with collections. While the set ensures all elements are unique, making it ideal for managing distinct data, a map offers a more efficient way to store and retrieve key-value pairs than traditional objects. The set includes methods like add
for adding elements, has
for checking the existence, and delete
for removal, while a map provides methods like set
to add key-value pairs, get
to retrieve values, and has
to check for the existence of keys. Both also offer properties like size
to determine the number of elements.
These data structures simplify operations that previously required cumbersome workarounds, enabling developers to write cleaner, more efficient, and maintainable code. By integrating maps and sets into their workflow, JavaScript developers can leverage modern programming techniques to handle collections effectively and elevate the quality of their applications.
Ready to master modern JavaScript? Dive deeper into Educative’s interactive course: “ES6 and Beyond.” From practical coding challenges to real-world projects, you’ll improve your skills and write cleaner, faster code.
JavaScript is a fundamental asset for any web developer. As an evolving language, new releases continue to refine it to make it more accessible for large-scale use. ECMA Script, or ES in short, is the standardized name for the programming language popularly known as JavaScript. The sixth release of the script is known as ES6 and features major enhancements which improve Javascript's usability. Writing and reading code is now easier with the introduction of features like Arrows, Symbols, etc. This course provides a practical view into all of the components present in ES6. We'll discuss the importance of each component, learning how and why it makes things simpler in Javascript. Interactive exercises and quizzes will help you adopt these modern coding practices for JavaScript. ES6 is rapidly growing in popularity, and this course is essential for anyone who wants to be fully immersed into JavaScript.
How do you fetch value from Map
in JavaScript?
How do you store data in a Map
in JavaScript?
What is the syntax of Map
?
Why does { id: 1 } !== { id: 1 }
true in a set?
Free Resources