WeakSet

WeakSet.prototype.add

Adds a new object or symbol to the WeakSet without preventing garbage collection of the value

Syntax

JavaScript
weakSet.add(value)

Parameters

ParameterTypeDescription
valueobjectThe object to add to the WeakSet

Return Value

The WeakSet object (allows chaining)

Examples

Basic Usage
const ws = new WeakSet()
const obj = { name: 'test' }
ws.add(obj)
console.log(ws.has(obj)) // true
Practical Example
const processed = new WeakSet<object>()
function processOnce(item: object) {
  if (processed.has(item)) return false
  processed.add(item)
  return true
}
Advanced Usage
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.