Sets, WeakSets, Maps and WeakMaps
Learn how to store unique values in sets and much more.
We'll cover the following...
What is a Set
? #
A Set
is an Object
where we can store unique values of any type.
Press + to interact
// create our setconst family = new Set();// add values to itfamily.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.
Press + to interact
const family = new Set(["Dad", "Mom", "Son"]);console.log(family.size);// 3console.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 ...
Access this course and 1400+ top-rated courses and projects.