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 WeakMap object.
On this page

Example

#
JavaScript
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' }))
Console
2
false

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

#
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

#
A string can’t be a key
JavaScript
const cache = new WeakMap()

try {
  cache.set('Emma', 1)
} catch (error) {
  console.log(error.name)
}

console.log(cache)
Console
TypeError
WeakMap {}
Data hidden outside the object
JavaScript
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'))
Console
Account { login: 'emma' }
true

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 WeakMap for caches and data attached to objects that may disappear, such as DOM elements.
  • In new classes, private fields #field are more convenient for hiding data.
  • If you need size, a list of keys, or to loop over entries, choose a regular Map.

Related entries

#

Spotted a mistake or missing an example? Write to us.