Home/Blog/Programming/JavaScript map and set tutorial: How to use new built-in classes
JavaScript Map and Set tutorial
Home/Blog/Programming/JavaScript map and set tutorial: How to use new built-in classes

JavaScript map and set tutorial: How to use new built-in classes

13 min read
May 15, 2025
content
The need for map and set in ES6
What is a map in JavaScript?
Key characteristics of a map in JavaScript
Map vs object in Javascript: Key differences
How to implement a map
Utilizing maps in JavaScript
Iterating through a map
Initialize a map with an iterable object
Get an element from a map by key
Get the number of elements in the map
Convert map keys or values to array
Other important map methods
Hands-on exercise with map
Solution breakdown
What is set in JavaScript?
Key characteristics of a set in Javascript
Set vs array: Key differences
Working with set: Methods and examples
filter/map with sets
Get the size of a set
Remove elements from a set
Invoke a callback function on each element
Other important set methods
Hands-on exercise: Playing with set in JavaScript
Solution breakdown
Common use cases of map and set in Java
When to use a map
When to use set
Real-world coding scenarios
Wrapping up!
Continue reading about JavaScript

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

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

Cover
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.

3hrs
Beginner
42 Challenges

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.

The need for map and set in ES6#

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?

Javascript (babel-node-es2024)
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.

What is a map in JavaScript?#

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.

Key characteristics of a map in JavaScript#

  • 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()).

Map vs object in Javascript: Key differences#

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 (Object.keys(), etc.)

Built-in iterators (keys(), values(), entries())

Size

Manually count

map.size provides the number of entries

Serialization

Limited support with JSON

Not directly supported

How to implement a map#

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.

Javascript (babel-node-es2024)
'use strict';
//START:DEFINE
const scores =
new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
console.log(scores.size);
//END:DEFINE
  • The scores map has been initialized with names and scores. The initial data may be any iterable with a pair of keys and values.
  • We add a key and value to the map using the set() method (line 7)
  • To figure out how many keys are currently in a map, we use the size property (line 9)

Note: Map.has(key) above will return the boolean value to indicate if the element associated with a specified key is in the map.

Utilizing maps in JavaScript#

Once we understand how to create maps in JavaScript, we can leverage their powerful features for efficient data management.

Iterating through a map#

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:

Javascript (babel-node-es2024)
'use strict';
//START:DEFINE
const scores =
new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
//END:DEFINE
for(const [name, score] of scores.entries()) {
console.log(`${name} : ${score}`);
}

We can also use the forEach method, which is an internal iterator.

Javascript (babel-node-es2024)
'use strict';
//START:DEFINE
const scores =
new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
//END:DEFINE
scores.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:

Javascript (babel-node-es2024)
'use strict';
//START:DEFINE
const scores =
new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
//END:DEFINE
scores.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.

Initialize a map with an iterable object#

You can also pass an iterable object to the Map() constructor:

let userRoles = new Map([
['sarah', 'admin'],
['bob', 'editor'],
['jill', 'subscriber']
]);

Get an element from a map by key#

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

Get the number of elements in the map#

We can use the size property to get the number of elements in our maps.

console.log(userRoles.size); // 3

Convert map keys or values to array#

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);

Other important map methods#

  • 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.

Hands-on exercise with map#

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

console.log(todo.get('learn JavaScript'));

done

console.log(todo.get('write elegant code'));

work-in-progress

console.log(todo.get('automate tests'));

work-in-progress

console.log(completedCount(todo));

1

The solution to this challenge is given below. Try it yourself first.

'use strict';
const createTodo = function() {
const todo = new Map();
//Add your code here
return todo;
};
const completedCount = function(map) {
//Add your code here
return;
};
const todo = createTodo(); //Returns a Map

Solution breakdown#

  • 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.

What is set in JavaScript?#

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.

Key characteristics of a set in Javascript#

  • 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().

Set vs array: Key differences#

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

forEach(), map(), etc.

values(), keys(), entries()

Conversion

Requires Set() for uniqueness

It can be converted to an array using the spread operator

Working with set: Methods and examples#

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.

Javascript (babel-node-es2024)
'use strict';
//START:CREATE
const names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);
//END:CREATE
//START:SIZE
console.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.

Javascript (babel-node-es2024)
'use strict';
//START:CREATE
const names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);
//END:CREATE
//START:ADD
names.add('Mike');
//END:ADD
//START:ADD2
names.add('Kate').add('Kara');
//END:ADD2
console.log(names.has('Brad'));
console.log(names.entries());
console.log(names.keys());
console.log(names.values());
//START:ITERATE1
for(const name of names) {
console.log(name);
}
//END:ITERATE1

filter/map with sets#

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.

Javascript (babel-node-es2024)
'use strict';
//START:CREATE
const names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);
//END:CREATE
//START:ADD
names.add('Mike');
//END:ADD
//START:ADD2
names.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

Get the size of a set#

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

Remove elements from a set#

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) {}

Invoke a callback function on each element#

To invoke a callback on every element of your set, use the forEach() method.

names.forEach(name => console.log(name.toUpperCase()));

Other important set methods#

  • 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.

Hands-on exercise: Playing with set in JavaScript#

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

console.log(mySet.has('apple'));

true

console.log(mySet.has('banana'));

false

console.log(mySet.size);

3

mySet.delete('orange'); console.log(mySet.size);

2

The solution is provided below, but try implementing it yourself first.

'use strict';
// Function to create and return a Set
const createSet = function() {
const set = new Set();
//Add your code here
return set;
};
Solution breakdown#
  • 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.

Common use cases of map and set in Java#

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:

When to use a map#

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.

When to use set#

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.

Real-world coding scenarios#

  • 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.

Wrapping up!#

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.

Cover
JavaScript In Practice: ES6 And Beyond

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.

10hrs
Beginner
41 Challenges
55 Illustrations

Frequently Asked Questions

How do you fetch value from Map in JavaScript?

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

How do you store data in a Map in JavaScript?

You can use the .set(key, value) method to store data in a Map.

Example:

let myMap = new Map();
myMap.set('age', 25);
myMap.set('city', 'New York');
console.log(myMap); // Output: Map { 'age' => 25, 'city' => 'New York' }

What is the syntax of Map?

The basic syntax of a Map is as follows:

let map = new Map([
  [key1, value1],
  [key2, value2],
  [key3, value]
]);

Example:

let users = new Map([
  ['id1', 'Alice'],
  ['id2', 'Bob']
]);
console.log(users.get('id1')); // Output: Alice

Why does { id: 1 } !== { id: 1 } true in a set?

Because JavaScript compares objects by reference, not value. Think of it like two identical twins—you can’t assume they’re the same person just because they look alike!


Written By:
Amanda Fawcett

Free Resources