DEV Community

Cover image for Sets in Javascript ES6

Sets in Javascript ES6

Damien Cosset on July 11, 2018

Introduction Before ES6, Javascript had no native implementation of Sets. What is a set? A set is a list of values that cannot contain d...
Collapse
 
nickytonline profile image
Nick Taylor

Thanks for the post Damien. You should do a follow up on Maps, WeakMaps. Maybe go into explaining how Weakmaps are great for meta data.

Collapse
 
damcosset profile image
Damien Cosset

Thank for the comment. I'm working on it ;)

Collapse
 
bernhardwebstudio profile image
Bernhard Webstudio

Thanks for the post. The last example is a little confusing to me: When setting obj = null, and afterwards testing with set.has(obj), I would expect the set to return false even if it still contains {} (the object), as the test is equal to set.has(null) and you never added null to the set. Or am I wrong?

Collapse
 
damcosset profile image
Damien Cosset

In that last example, we added a reference to the object, inside the variable obj. By setting obj to null, we eliminate the last reference to the object we stored in our set. Therefore, because this is a WeakSet, the object is garbage-collected in order to free memory.

Hope it's clear :)

Collapse
 
ben profile image
Ben Halpern

Probably the cleanest cover image you've had Damian! 😋

Collapse
 
math2001 profile image
Mathieu PATUREL

So, if there are no other references to an object, the reference inside the set will disappear.

I never took the time to actually learn what "weak" things were. Thanks :D