Search⌘ K
AI Features

Sets, WeakSets, Maps and WeakMaps

Explore the concepts of Sets, WeakSets, Maps, and WeakMaps in JavaScript. Learn how these data structures store unique values or key-value pairs, their iteration methods, and automatic memory management through weak references. Understand how to use Sets to remove duplicates from arrays and the differences in behavior and use cases between these collections.

What is a Set? #

A Set is an Object where we can store unique values of any type.

Javascript (babel-node)
// create our set
const family = new Set();
// add values to it
family.add("Dad");
console.log(family);
// Set [ "Dad" ]
family.add("Mom");
console.log(family);
// Set [ "Dad", "Mom" ]
family.add("Son");
console.log(family);
// Set [ "Dad", "Mom", "Son" ]
family.add("Dad");
console.log(family);
// Set [ "Dad", "Mom", "Son" ]

As you can see, at the end we tried to add “Dad” again at line 17, but the Set still remained the same because a Set can only take unique values.

Let’s continue using the same Set and see what methods we can use on it.

Node.js
const family = new Set(["Dad", "Mom", "Son"]);
console.log(family.size);
// 3
console.log(family.keys());
// SetIterator {"Dad", "Mom", "Son"}
console.log(family.entries());
// SetIterator {"Dad", "Mom", "Son"}
console.log(family.values());
// SetIterator {"Dad", "Mom", "Son"}
family.delete("Dad");
console.log(family);
// Set [ "Mom", "Son" ]
family.clear();
console.log(family);
// Set []

As you can see, a Set has a size property and we can delete an item from it or use clear to delete all the items from it.

We can also notice that a Set does not ...