Table of contents
1.
Introduction
2.
What is a Map?
2.1.
Creation of Map:
2.2.
Example of a Map:
2.3.
Methods and Properties of Map
2.4.
Initialisation of a Map:
2.5.
Converting Keys or Values to Arrays:
3.
What is a Set?
3.1.
Creation of Set:
3.2.
Methods and Properties of Set
3.3.
Example of a Set:
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Map and Set in JavaScript

Introduction

JavaScript offered only arrays and objects in the initial versions to store collections. Keyed collections are stored in objects, and for storing ordered collections, arrays were utilised.

 

But to solve complex real-life problems, these data structures weren't enough. That's why with ES6, JavaScript offers built-in classes for sets and maps that make the programming easier to maintain. 

 

In this article, we'll be exploring the map and set data structures in JavaScript. So, let's get started!

What is a Map?

Before ES6, many JavaScript developers used to use the objects to map keys to their values. However, using an object as a map has limitations.

For example:

 

  • There is no complete way to iterate over keys, and the keys() method converts fields to given strings, which leads to the collision of keys.
  • There is also no simple way to add new keys and values to the object.

 

ES6 introduced new features like built-in classes, including a collection type called map, which tends to hold key-value pairs of any type. Unlike the previous generation object approach, the new Map object can even remember key insertion order.

 

In simple terms, we can conclude that a JavaScript Map is an associative collection of distinct keys and their corresponding values. Both keys and values can be any type, either primitive or object. This is a significant data structure with many practical uses.

Creation of Map:

let map = new Map([iterable]);

 

  • The map () accepts an optional iterable object whose elements are key-value pairs.

 

Example of a Map:

'use strict';
const scores = new Map([['Shubham', 12], ['Vaishnavi', 13], ['Juhi', 10], ['Priyanka', 12]]);
scores.set('sohuard', 14);
console.log(scores.size);

Output:

5

 

Explanation

  • The map scores that we have created above have been initialised with names and scores values. The initial data of the map may be iterable with the help of a pair of keys and values.
  • We added a key and value to the map using the set() method with key "souhard".
  • To figure out no of keys that are currently on the map, we used the size property. 

Methods and Properties of Map

As an object, a Map is a collection of keyed data items. The main difference is that the map accepts any key. 

 

The table below contains some of the methods of Maps in JavaScript.

 

Method Description
new map () creates the map.
map.set(key, value) stores the value by the key.
map.get(key) returns the value by the key, undefined if the key doesn’t exist in the map.
map.has(key) returns true if the key exists, false otherwise.
map.delete(key) removes the value by the key.
map.forEach(callback[, thisArg]) invokes a callback for each key-value pair in the map in the insertion order. The optional thisArg parameter sets this value for each callback.
map.clear() removes everything from the map.
map.size returns the current element count.
map.keys() returns an iterable for keys.
map.entries() returns an iterable for entries [key, value].
map.values() returns an iterable for values.

 

Example: In the code below, we can extract the name and score for each key-value pair present in the map:

'use strict';
const scores = new Map([['Shubham', 12], ['Vaishnavi', 13], ['Juhi', 10], ['Priyanka', 12]]);
scores.set('Sohuard', 14);
console.log(scores.size);
for(const [name, score] of scores.entries()) 
{
  console.log(`${name} : ${score}`);
}

Output:

5

Shubham : 12

Vaishnavi : 13

Juhi : 10

Priyanka : 12

Sohuard : 14

Initialisation of a Map:

We can pass an iterable object to the Map() constructor. Let’s understand with the help of an example.

 

Example:

let userRoles = new Map([
    [shubham, 'admin'],
    [Vaishnavi, 'editor'],
    [Juhi, 'subscriber']
]);

 

Converting Keys or Values to Arrays:

When working with an array rather than an iterable object, we can use the spread operator. This will help us convert our keys or values into arrays. Let’s see with the help of an example:

 

Code Snippet: The below example creates an array of keys.

var keys = [...userRoles.keys()];
console.log(keys);

 

And the below piece of code will convert the values of elements to an array:

 

var roles = [...userRoles.values()];
console.log(roles);

 

This was all about maps in JavaScript. Let's get familiar with sets in JS now.

What is a Set?

Set is another new collection that ES6 introduced. The Array class of JavaScript works with an ordered data collection, but not perfectly with unordered collections or when values held in the collection set are unique. That’s why Javascript introduced set collection in ES6.

 

A set is a unique collection of primitive data types and objects. Duplicates are not permitted in sets. 

 

In a set, we can either create an empty set and add objects or initialise a set with its contents of an iterable (similar to an array).

 

Creation of Set:

The Set() constructor creates set objects that store unique values of any type.

 

Syntax:

new Set()
new Set(iterable)

Methods and Properties of Set

The table below contains some of the methods of Maps in JavaScript.

 

Method Description
new Set() creates a new Set object.
Set.size returns the number of values in the Set object.
Set.add(value) appends a value to the Set object. Returns the Set object with added value.
Set.clear() removes all elements from the Set object.
Set.delete(value) removes the element associated with the value and returns a boolean asserting whether an element was successfully removed or not.
Set.has(value) checks whether an element is present with the given value in the Set object or not.
Set.values() returns a new iterator object that yields the values for each set object in insertion order.
Set.keys() same as Set.values().
Set.entries() returns a new iterator object that contains an array of [value, value] for each element in the Set object, in insertion order.
Set.forEach(callbackFn[, thisArg]) Invokes a callback once for each value present in the Set object, in insertion order.

 

Example of a Set:

A simple example showing the essential operation of the set in JavaScript is given below.

const Set1 = new Set()

Set1.add(1)           // Set [ 1 ]
Set1.add(5)           // Set [ 1, 5 ]
Set1.add(5)           // Set [ 1, 5 ]
Set1.add('abc') // Set [ 1, 5, 'abc' ]

// Adding an object reference to the set.
const obj = {a: 1, b: 2}
Set1.add(obj)

Set1.add({a: 1, b: 2})// o is referencing a different object here

Set1.has(1)              // true
Set1.has(3)              // false, since 3 is not present
Set1.has(5)              // true
Set1.has(Math.sqrt(25))  // true
Set1.has('abc') // true
Set1.has(obj)       // true

Set1.size         // 5

Set1.delete(5)    // removes 5 from the set
Set1.has(5)       // false, 5 has been removed

Set1.size         // 4, since we just removed one value

console.log(Set1)
// logs Set(4) { 1, "some text", {...}, {...} }

You can try it by yourself on an online javascript compiler.

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

1)What is a Map in JavaScript?

The map is an associative collection of distinct keys and their corresponding values. Both keys and values can be any type, either primitive or object.


2)What is a Set in JavaScript?

A set is a unique(data) collection of primitives and objects, and duplicates are not permitted.

Key Takeaways

In this blog, we introduced you to map and set in JavaScript. We have also included some of the basic operations on these data structures, along with some examples.

 

You can use Coding Ninjas Studio to practise questions on web development and use the Coding Ninja Self-paced Web development to grasp numerous web development concepts.

 

Happy Learning!

 

Live masterclass