WeakMap
A map with objects as keys that doesn’t keep them in memory: the entry disappears along with the unused object.
- Returns
- A new
WeakMapobject.
Example
#const visits = new WeakMap()
function trackVisit(user) {
visits.set(user, (visits.get(user) ?? 0) + 1)
return visits.get(user)
}
const emma = { name: 'Emma' }
trackVisit(emma)
console.log(trackVisit(emma))
console.log(visits.has({ name: 'Emma' }))Definition and usage
#WeakMap works similarly to Map, but it’s meant for attaching data to objects: the keys are objects, and trying to use a string or a number throws a TypeError. The map holds its keys "weakly": once nothing else in the program references the object used as a key, the JavaScript engine can remove it from memory along with its associated value.
That makes WeakMap well suited for attaching extra data to objects you don’t control, such as DOM elements or objects from a library, without risking a memory leak. When an element is removed from the page and forgotten, its data disappears with it.
WeakMap has only four methods: set(), get(), has(), and delete(). It has no size, no clear(), and no way to iterate over its entries, because its contents can change at any moment as a result of garbage collection. If you need a list of all entries, use a regular Map.
Syntax
#new WeakMap()
new WeakMap(iterable)
weakMap.set(key, value)
weakMap.get(key)
weakMap.has(key)
weakMap.delete(key)Parameters
#iterable
optional
An array of[object, value]pairs the map is initially filled with.
More examples
#const cache = new WeakMap()
try {
cache.set('Emma', 1)
} catch (error) {
console.log(error.name)
}
console.log(cache)const passwords = new WeakMap()
class Account {
constructor(login, password) {
this.login = login
passwords.set(this, password)
}
checkPassword(attempt) {
return passwords.get(this) === attempt
}
}
const account = new Account('emma', 'secret123')
console.log(account)
console.log(account.checkPassword('secret123'))The password isn’t a property of the object, so it doesn’t show up in the console or in Object.keys(). In new classes, the private field #password gives the same effect.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Use
WeakMapfor caches and data attached to objects that may disappear, such as DOM elements. - In new classes, private fields
#fieldare more convenient for hiding data. - If you need
size, a list of keys, or to loop over entries, choose a regularMap.
Related entries
#- MapA collection of key-value pairs where the key can be any value and insertion order is preserved.
- SetA collection of unique values: each value can appear in the set only once.
- classDefines a class: a template for creating objects that share the same fields and methods.
- Object.create()Creates a new object with the given prototype.
- WeakSetA set of objects that doesn’t keep them in memory. Used for marking objects, e.g. ones already handled.
Spotted a mistake or missing an example? Write to us.