Map and Set

Learn the differences and practical uses of Map and Set in JavaScript with detailed explanations, examples, and methods.

Loading...
Map and Set

In JavaScript, objects and arrays are often used to store and manage data.

But JavaScript also provides four powerful built-in data structures that are often more useful and efficient than plain objects or arrays when you need uniqueness or flexible key types.

  • Set
  • Map
  • WeakSet
  • WeakMap

Let’s learn about each one in detail.

Set in JavaScript

A Set is a collection of unique values.

Any duplicate items will be automatically removed from the set.

Creating a Set

You can create a Set by using new Set() syntax.

const fruits = new Set();
 
console.log(fruits); // Output: Set []

Set Property (size)

The size property returns the number of values in the set.

console.log(fruits.size); // Output: 0

Set Methods

JavaScript provides the following methods to work with sets.

add(value):

The add(value) method adds a value to the set, if it doesn't already exist.

If the value already exists, then it will ignore that value.

const fruits = new Set();
 
fruits.add("apple");
fruits.add("banana");
fruits.add("apple"); // This is duplicate, so it will be ignored.
 
console.log(fruits); // Output: Set ["apple", "banana"]

has(value):

The has(value) method is used to check if a set contains a specific value. It returns true if the value exists, otherwise false.

fruits.has("apple"); // Output: true
fruits.has("plum"); // Output: false

delete(value):

The delete(value) method is used to remove a value from the set.

fruits.delete("apple");
console.log(fruits); // Output: Set ["banana"]

clear():

The clear() method is used to remove all the values from a set.

fruits.clear();
console.log(fruits); // Output: Set []

values():

The values() method returns a new iterator object with all the values in the Set (in insertion order).

const fruits = new Set(["apple", "banana", "grapes", "plum"]);
 
for (const value of fruits.values()) {
  console.log(value);
}
 
// Output:
// apple
// banana
// grapes
// plum

keys():

The keys() method is the same as values() for a Set.

const fruits = new Set(["apple", "banana", "grapes", "plum"]);
 
for (const key of fruits.keys()) {
  console.log(key);
}
 
// Output:
// apple
// banana
// grapes
// plum

entries():

The entries() method returns an iterator of [value, value] pairs, similar to [key, value] in Map.

In a Set, key and value are the same.

const fruits = new Set(["apple", "banana", "grapes", "plum"]);
 
for (const [key, value] of fruits.entries()) {
  console.log([key, value]);
}
 
// Output:
// [ "apple", "apple" ]
// [ "banana", "banana" ]
// [ "grapes", "grapes" ]
// [ "plum", "plum" ]

Iterating a Set

You can use the for..of or forEach loop to iterate through the values of a set.

const fruits = new Set(["apple", "banana", "grapes", "plum"]);
 
for (const fruit of fruits) {
  console.log(fruit);
}
 
// or
fruits.forEach((fruit) => console.log(fruit));
 
// Output:
// apple
// banana
// grapes
// plum

Use Case of Set

Set is useful for removing duplicate items from an array.

const dupes = [1, 2, 2, 3, 1];
const unique = [...new Set(dupes)];
console.log(unique); // Output: [1, 2, 3]

Map in JavaScript

A Map is a collection of key-value pairs.

It's like an object, but more flexible and powerful.

Creating a Map

You can create a Map by using new Map() syntax.

const admin = new Map();
 
console.log(admin); // Output: Map(0)

Map Property (size)

The size property returns the number of entries in the map.

console.log(admin.size); // Output: 0

Map Methods

JavaScript provides the following methods to work with maps.

set(key, value):

The set(key, value) method adds or updates a key-value pair.

const admin = new Map();
 
admin.set("name", "Shefali");
admin.set("age", 26);
 
console.log(admin); // Output: Map { name → "Shefali", age → 26 }

get(key):

The get(key) method returns the value for the key.

console.log(admin.get("name")); // Output: Shefali

has(key):

The has(key) method is used to check if a key exists in a map. It returns true if the value exists, otherwise false.

admin.has("Profession"); // Output: false
admin.has("age"); // Output: true

delete(key):

The delete(key) method removes a key-value pair.

admin.delete("age");
console.log(admin.has("age")); // Output: false

clear():

The clear() method removes all key-value pairs.

admin.clear();
console.log(admin.size); // Output: 0

keys():

The keys() method returns a new iterator object containing the keys in insertion order.

const map = new Map([
  ["name", "Shefali"],
  ["age", 26],
]);
 
for (const key of map.keys()) {
  console.log(key);
}
 
// Output:
// name
// age

values()

The values() method returns a new iterator object containing the values in insertion order.

const map = new Map([
  ["name", "Shefali"],
  ["age", 26],
]);
 
for (const value of map.values()) {
  console.log(value);
}
 
// Output:
// Shefali
// 26

entries()

The entries() method returns a new iterator object containing [key, value] pairs in insertion order.

This is the default iterator for a Map.

const map = new Map([
  ["name", "Shefali"],
  ["age", 26],
]);
 
for (const [key, value] of map.entries()) {
  console.log(key, value);
}
 
// Output:
// name Shefali
// age 26

You can also just do:

const map = new Map([
  ["name", "Shefali"],
  ["age", 26],
]);
 
for (const [key, value] of map) {
  console.log(key, value);
}
 
// Output:
// name Shefali
// age 26

Iterating a Map

You can use the for..of or forEach loop to iterate through the entries of a map.

const admin = new Map([
  ["name", "Shefali"],
  ["role", "Developer"],
]);
 
for (const [key, value] of admin) {
  console.log(key, value);
}
 
// or
admin.forEach((value, key) => {
  console.log(key, value);
});
 
// Output:
// name Shefali
// role Developer

Use Case of Map

By using map, you can use objects as keys.

const user1 = { id: 1 };
const user2 = { id: 2 };
 
const scores = new Map();
scores.set(user1, 95);
scores.set(user2, 87);
 
console.log(scores.get(user1)); // Output: 95

WeakMap and WeakSet in JavaScript!


Support my work!