WeakMap.prototype.set
Adds or updates an element with a specified key and value to a WeakMap where the key must be an object or symbol
Syntax
weakMap.set(key, value)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | object | The key of the element (must be an object) |
| value | any | The value of the element |
Return Value
The WeakMap object (allows chaining)
Examples
const wm = new WeakMap()
const key = {}
wm.set(key, 'metadata')
console.log(wm.get(key)) // 'metadata'const privateData = new WeakMap<object, { count: number }>()
function createCounter() {
const obj = {}
privateData.set(obj, { count: 0 })
return obj
}const cache = new WeakMap<object, string>()
function expensive(obj: object) {
if (cache.has(obj)) return cache.get(obj)!
const result = JSON.stringify(obj)
cache.set(obj, result)
return result
}Understanding WeakMap.prototype.set
The WeakMap.prototype.set method in JavaScript adds or updates an element with a specified key and value to a WeakMap where the key must be an object or symbol. It belongs to the WeakMap object and is one of the most widely used methods for working with weakmap values in modern JavaScript and TypeScript applications.
The method signature is weakMap.set(key, value). It accepts 2 parameters: key, value. When called, it returns the weakmap object (allows chaining). Understanding when and how to use set() helps you write more expressive, readable code.
Common use cases for WeakMap.prototype.set include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like weakmap-get, weakmap-has, weakmap-delete, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for WeakMap.prototype.set 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
WeakMap.prototype.getReturns the value associated with the specified key in the WeakMap, or undefined if the key is not present
WeakMap.prototype.hasReturns a boolean indicating whether an element with the specified key exists in the WeakMap
WeakMap.prototype.deleteRemoves the specified element from the WeakMap by its key
More WeakMap Methods
Other methods in the WeakMap object
Related Tools
More WeakMap Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.