JavaScript WeakSet()
The WeakSet() constructor creates WeakSet objects.
A WeakSet stores unique objects.
Unlike Set objects, WeakSet values must be objects.
WeakSet values are held weakly and can be removed automatically when no longer used elsewhere.
Syntax
new WeakSet()
new WeakSet(iterable)
Parameters
| Parameter | Description |
|---|---|
| iterable | Optional. An iterable object containing objects. |
Return Value
| Call | Returns |
|---|---|
new WeakSet() |
A WeakSet object |
new WeakSet(iterable) |
A WeakSet object initialized with values |
Creating a WeakSet
Example
const ws = new WeakSet();
Object Values Only
WeakSet values must be objects.
Valid
const person = {};
const ws = new WeakSet();
ws.add(person);
Invalid
const ws = new WeakSet();
ws.add("John"); // Error
WeakSet vs Set
| WeakSet | Set |
|---|---|
| Values must be objects | Values can be any type |
| Not iterable | Iterable |
| No size property | Has a size property |
| Values may be removed automatically | Values remain until removed |
Unique Values
A WeakSet stores unique objects.
Adding the same object more than once has no effect.
Example
const person = {};
const ws = new WeakSet();
ws.add(person);
ws.add(person);
Common Methods
add()has()delete()
Not Iterable
WeakSet objects are not iterable.
WeakSet objects do not provide keys(), values(), entries(), or forEach().
WeakSet values must be objects.
WeakSet objects are not iterable and do not have a size property.
Typical Use
WeakSet objects are often used to track objects without preventing those objects from being removed from memory.
Example
const visited = new WeakSet();
const person = {};
visited.add(person);
Object Hierarchy
WeakSet objects inherit from Object.
Object └─ WeakSet
| What | Value |
|---|---|
| Constructor Type | Function |
| Creates | WeakSet objects |
| Inherits From | Object |
| Iterable | No |
| Object Values Required | Yes |
Browser Support
WeakSet() is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
| Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |