Skip to content

10 Map & Sets

Biswajit Sundara edited this page May 1, 2023 · 1 revision

In ES6, two new built-in collection types were added to JavaScript, the Map and the Set.

Map

  • The Map object is a collection of key-value pairs where keys can be any data type, and values can be any data type.
  • Each key in the Map can only appear once, and it maintains the order of insertion.
  • The Map object has various methods for accessing, adding, and removing elements.

Here is an example of using the Map object:

// create a new Map object
const myMap = new Map();

// add some key-value pairs to the Map
myMap.set('name', 'John');
myMap.set('age', 30);
myMap.set(true, 'yes');

// get the value for a specific key
console.log(myMap.get('name')); // output: John

// check if a key exists in the Map
console.log(myMap.has(true)); // output: true

// remove a key-value pair from the Map
myMap.delete('age');

// get the number of key-value pairs in the Map
console.log(myMap.size); // output: 2

// loop through the Map using forEach
myMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

Set

The Set object is a collection of unique values of any data type.

  • It does not allow duplicates and maintains the order of insertion.
  • The Set object has various methods for accessing, adding, and removing elements.

Here is an example of using the Set object:

// create a new Set object
const mySet = new Set();

// add some values to the Set
mySet.add('apple');
mySet.add('banana');
mySet.add('orange');

// check if a value exists in the Set
console.log(mySet.has('banana')); // output: true

// remove a value from the Set
mySet.delete('orange');

// get the number of values in the Set
console.log(mySet.size); // output: 2

// loop through the Set using forEach
mySet.forEach((value) => {
  console.log(value);
});

Clone this wiki locally