Keyed Collection in JavaScript

Set, Map, WeakSet, WeakMap

Nikhil Swain
3 min readJan 25, 2020

Set

Sets are ordered lists of values that contain no duplicates.You can iterate through the elements of a set in insertion order. A value in the set may only occur once it is unique in the set’s collection.

What’s intersting about set is NaN and undefined can also be stored in a Set. All NaN values are equated (i.e. NaN is considered the same as NaN , even though NaN !== NaN).
Syntax :
let mySet = new Set();

For instance :

Properties of Set :

Iterating Sets :

Map

Map is a collection of element where each element is stored as a collection of key,value pair.Or simply said, Map is collection of keyed data items, just like Objects.But the only difference is that Map allows Key of any type. The detailed difference between Map and Object is given here.
Syntax :
let myMap = new Map([[key,value]]);

For instance :

Properties of Map :

Map can also use objects as keys :

Iterating Maps :

WeakSet

WeakSet objects are collection of objects. Objects in a WeakSet is collection of unique objects just like Sets. The major difference of a WeakSet with the set is that a WeakSet is a collection of objects and not values of some particular type.
Syntax :
let carSet = new WeakSet();

For instance :

Properties :

WeakMap

WeakMap object is used to store the elements as key-value pair where keys are weakly referenced.The thing to note is keys can only be objects .
Syntax :
let carMap = new WeakMap();

Properties :

Reference : MDN

--

--