WeakSet.prototype.add
Adds a new object or symbol to the WeakSet without preventing garbage collection of the value
Syntax
weakSet.add(value)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | object | The object to add to the WeakSet |
Return Value
The WeakSet object (allows chaining)
Examples
const ws = new WeakSet()
const obj = { name: 'test' }
ws.add(obj)
console.log(ws.has(obj)) // trueconst processed = new WeakSet<object>()
function processOnce(item: object) {
if (processed.has(item)) return false
processed.add(item)
return true
}const ws = new WeakSet<HTMLElement>()
document.querySelectorAll('.lazy').forEach(el => {
ws.add(el as HTMLElement)
})Understanding WeakSet.prototype.add
The WeakSet.prototype.add method in JavaScript adds a new object or symbol to the WeakSet without preventing garbage collection of the value. It belongs to the WeakSet object and is one of the most widely used methods for working with weakset values in modern JavaScript and TypeScript applications.
The method signature is weakSet.add(value). It accepts 1 parameter: value. When called, it returns the weakset object (allows chaining). Understanding when and how to use add() helps you write more expressive, readable code.
Common use cases for WeakSet.prototype.add include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like weakset-has, weakset-delete, weakmap-set, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for WeakSet.prototype.add is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More WeakSet Methods
Other methods in the WeakSet object
Related Tools
More WeakSet Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.