Advanced25 min read

Map & Set

Explore Map and Set collections for storing unique values and key-value pairs with any type of key.

Map Basics

A Map is a collection of key-value pairs where keys can be any type — objects, functions, primitives, even NaN. This is a major advantage over plain objects, where keys are always converted to strings.

Creating and using a Map:

javascript
const map = new Map();

// Setting values
map.set('name', 'Alice');
map.set(42, 'the answer');
map.set(true, 'yes');

// Getting values
console.log(map.get('name')); // 'Alice'
console.log(map.get(42));     // 'the answer'

// Checking existence
console.log(map.has('name')); // true
console.log(map.has('age'));  // false

// Size
console.log(map.size); // 3

// Deleting
map.delete(42);
console.log(map.size); // 2

// Clearing all entries
map.clear();
console.log(map.size); // 0

You can also initialize a Map with an array of [key, value] pairs:

javascript
const map = new Map([
  ['name', 'Alice'],
  ['age', 30],
  ['city', 'Paris']
]);

When to use Map over an object:

  • Keys are not strings (numbers, objects, etc.).
  • You need to know the size easily (.size).
  • You need frequent additions and deletions.
  • You need guaranteed insertion order during iteration.

Iterating Maps

Maps are iterable and provide several methods for accessing their contents.

Iteration methods:

javascript
const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);

// Keys
for (const key of map.keys()) {
  console.log(key); // 'a', 'b', 'c'
}

// Values
for (const value of map.values()) {
  console.log(value); // 1, 2, 3
}

// Entries (key-value pairs)
for (const [key, value] of map.entries()) {
  console.log(key, value); // 'a' 1, 'b' 2, 'c' 3
}

for...of with destructuring — iterating a Map directly gives you entries:

javascript
for (const [key, value] of map) {
  console.log(`${key} => ${value}`);
}

forEach method:

javascript
map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

Converting between Maps and arrays:

javascript
// Map to array of entries
const entries = [...map]; // [['a', 1], ['b', 2], ['c', 3]]

// Array of entries to Map
const newMap = new Map(entries);

// Map keys to array
const keys = [...map.keys()]; // ['a', 'b', 'c']

Set Basics

A Set is a collection of unique values. If you try to add a value that already exists, it is simply ignored.

Creating and using a Set:

javascript
const set = new Set();

// Adding values
set.add(1);
set.add(2);
set.add(3);
set.add(2); // Ignored — 2 already exists

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

// Checking existence
console.log(set.has(2)); // true
console.log(set.has(4)); // false

// Deleting
set.delete(2);
console.log(set.size); // 2

// Clearing
set.clear();

The most common use case — removing duplicates from an array:

javascript
const numbers = [1, 2, 3, 2, 4, 3, 5, 1];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]

Sets are also iterable:

javascript
const set = new Set(['apple', 'banana', 'cherry']);

for (const fruit of set) {
  console.log(fruit);
}

set.forEach(value => console.log(value));

const array = [...set]; // Convert to array

Sets use strict equality (===) for comparison, with the special case that NaN equals NaN in a Set (unlike normal ===).

WeakMap & WeakSet

JavaScript also provides WeakMap and WeakSet — specialized versions of Map and Set with important differences.

Key restrictions:

  • WeakMap keys must be objects (not primitives).
  • WeakSet values must be objects.

Weak references:

The "weak" in WeakMap/WeakSet means the references to keys (or values) are weakly held. If there are no other references to the key object, it can be garbage collected — even if it is still in the WeakMap.

javascript
let user = { name: 'Alice' };
const cache = new WeakMap();
cache.set(user, 'cached data');

user = null; // The { name: 'Alice' } object can now be garbage collected

No iteration methods — you cannot iterate over a WeakMap or WeakSet. They have no .size, .keys(), .values(), .entries(), or .forEach(). This is because entries can disappear at any time due to garbage collection.

Common use cases:

  • Private data — store private properties associated with objects.
  • Caching — cache computed values without preventing garbage collection.
  • DOM node metadata — attach data to DOM elements that is cleaned up when the element is removed.
javascript
const metadata = new WeakMap();

function processElement(el) {
  if (!metadata.has(el)) {
    metadata.set(el, { visits: 0 });
  }
  metadata.get(el).visits++;
}

Map & Set in Action

html
<div id="output"></div>

<script>
  // === Map example: word frequency counter ===
  const words = ['hello', 'world', 'hello', 'js', 'world', 'hello'];
  const frequency = new Map();

  for (const word of words) {
    frequency.set(word, (frequency.get(word) || 0) + 1);
  }

  // === Set example: remove duplicates ===
  const numbers = [4, 2, 7, 2, 9, 4, 7, 1];
  const unique = [...new Set(numbers)].sort((a, b) => a - b);

  const output = document.getElementById('output');
  let html = '<h4>Word Frequencies (Map):</h4><ul>';

  for (const [word, count] of frequency) {
    html += `<li>${word}: ${count}</li>`;
  }

  html += '</ul>';
  html += `<h4>Unique Sorted Numbers (Set):</h4>`;
  html += `<p>[${unique.join(', ')}]</p>`;

  output.innerHTML = html;
</script>

How do you remove duplicates from an array using Set?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.