ECMAScript 6: what is WeakSet for?

it’s not being removed from the WeakSet. Why is that?

Most likely because the garbage collector has not yet run. However, you say you are using Traceur, so it just might be that they’re not properly supported. I wonder how the console can show the contents of a WeakSet anyway.

What is the point of adding objects to WeakSets directly?

There is absolutely no point of adding object literals to WeakSets.

What is the practical use of WeakSet if we cannot even iterate through it nor get the current size?

All you can get is one bit of information: Is the object (or generically, value) contained in the set?

This can be useful in situations where you want to “tag” objects without actually mutating them (setting a property on them). Lots of algorithms contain some sort of “if x was already seen” condition (a JSON.stringify cycle detection might be a good example), and when you work with user-provided values the use of a Set/WeakSet would be advisable. The advantage of a WeakSet here is that its contents can be garbage-collected while your algorithm is still running, so it helps to reduce memory consumption (or even prevents leaks) when you are dealing with lots of data that is lazily (possibly even asynchronously) produced.

Leave a Comment