JavaScript Map
and Set
Introduction
Map
and Set
are two powerful data structures introduced in ES6 that allow storing unique values and key-value pairs efficiently.
JavaScript Set
A Set
is a collection of unique values. Unlike arrays, it does not allow duplicate elements.
Creating a Set
Adding Elements to a Set
Checking Set Size
Checking if a Value Exists
Deleting Elements from a Set
Iterating Over a Set
Converting a Set to an Array
Clearing a Set
JavaScript Map
A Map
is a collection of key-value pairs where keys can be any type (objects, functions, etc.), unlike plain objects which only allow strings/symbols as keys.
Creating a Map
Adding Key-Value Pairs
Getting Values
Checking If a Key Exists
Checking Map Size
Deleting a Key
Iterating Over a Map
Converting a Map to an Array
Clearing a Map
Differences Between Map
and Object
Feature | Map | Object |
---|---|---|
Key types | Any type (objects, functions, etc.) | Strings or symbols only |
Order | Keys remain in insertion order | No guaranteed order |
Iteration | Easy with .forEach() or for...of | Requires Object.keys() , Object.values() , or Object.entries() |
Performance | Optimized for frequent additions/removals | Not optimized for frequent changes |
Summary
✔ Set
stores unique values (no duplicates)
✔ Map
stores key-value pairs
✔ Map
keys can be any type
✔ Set
and Map
support iterators (for...of
, .forEach()
)
✔ Set
is useful for removing duplicates from an array
✔ Map
is better than objects when keys are not strings
Now you know how to use Map
and Set
in JavaScript! Let me know if you need more examples. 😊