Implementing Maps and Sets with Node.js and JavaScript
Map and Set in modern JavaScript: any-type keys, deduplication, and when to choose them over plain objects or arrays in practice.
Map and Set in modern JavaScript: any-type keys, deduplication, and when to choose them over plain objects or arrays in practice.
{} only allows string/symbol keys; arrays do not dedupe. Map and Set (ES6) cover object-keyed caches and unique collections without hacks.
What you'll learn:
Map API: set, get, has, deleteSet for uniquenessMap vs plain objectsPrerequisites: hash tables (ep. 8).
Map and Set: key-value and uniquenessMaps and Sets are well-known data structures; we often use them daily without thinking of them as “structures” the way we do arrays or trees. Maps store key–value pairs with unique keys. Sets store unique values. In the ECMAScript 6 (ES6) era, JavaScript and Node.js gained built-in Map and Set types that make working with these patterns clearer and often more efficient.
A Map is a collection of key → value pairs where each key is unique. Values can be any type (number, object, etc.). Unlike plain objects, map keys can be any type too—including objects, functions, or primitives.
A Set is a collection of unique values. Values can be any type. Sets are useful whenever you must avoid duplicates.
Open your editor, create map-and-set.js, and start with Map:
const map = new Map()
map.set('key', 'value')
map.set({}, 'object as key')
map.set(() => {}, 'function as key')
map.set(1, 'number as key')
map.set('key2', { key: 'key in the map value object' })
console.log(
What this does:
new Map() creates an empty map.set(key, value) inserts or updates a pair.get(key) reads a value; has(key) checks membership; delete(key) removes a key.Now the Set:
const set = new Set()
set.add('item1')
set.add('item2')
set.add('item3')
set.add('item4')
set.add('item5')
console.log(`set:`, set)
console.log(`set has "item2":`, set.has
add inserts a value; duplicates are ignored.has tests membership; keys() returns an iterator over entries (values behave like keys in a set).delete removes a value.Use a Map when you need fast key–value access and updates—caches, indexes, or any structure where keys are not limited to strings/symbols in the way plain objects are.
Use a Set when the collection must not contain duplicates—deduping IDs, tracking active sessions, or a todo list where the same item should not appear twice (as a simple example).
NaNmap.set(obj, 1) only reads back with the same object reference.
Set uses SameValueZero — NaN equals NaN, unlike ===.
| Use | When |
|---|---|
| Map | key → value, any key type |
| Set | membership / dedupe |
| simple string-key records |
Where did Map or Set unblock you? Flag mistakes in the post.
Get new posts and videos by email as soon as they are out.