Explore Map and Set collections for storing unique values and key-value pairs with any type of key.
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:
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); // 0You can also initialize a Map with an array of [key, value] pairs:
const map = new Map([
['name', 'Alice'],
['age', 30],
['city', 'Paris']
]);When to use Map over an object:
.size).Maps are iterable and provide several methods for accessing their contents.
Iteration methods:
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:
for (const [key, value] of map) {
console.log(`${key} => ${value}`);
}forEach method:
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
});Converting between Maps and arrays:
// 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']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:
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:
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:
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 arraySets use strict equality (===) for comparison, with the special case that NaN equals NaN in a Set (unlike normal ===).
JavaScript also provides WeakMap and WeakSet — specialized versions of Map and Set with important differences.
Key restrictions:
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.
let user = { name: 'Alice' };
const cache = new WeakMap();
cache.set(user, 'cached data');
user = null; // The { name: 'Alice' } object can now be garbage collectedNo 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:
const metadata = new WeakMap();
function processElement(el) {
if (!metadata.has(el)) {
metadata.set(el, { visits: 0 });
}
metadata.get(el).visits++;
}<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?