Weakmap in javascript
Tags: javascript, typescript, node, webdev
Published: 2020-12-10 16:48:46

Let's remember on Garbage Collector !

```js
let obj = { name: 'toto' }

// The object { name: 'toto' } can be accessed
// since obj has the reference to it

// overwrite the reference
obj = null

// the object will be removed from the memory
// since we have lost all reference on it
```
Another exemple, 

```js
let obj = { name: 'toto' }
let arr = [ obj ]

obj = null
```
In this exemple, the object `{ name: 'toto' }` will not be removed since the array keep reference on it !

### What is the difference between strong and weak reference ?

In fact, most variables in javascript keep a Strong reference on an object. For example the array above keeps a **strong** reference on the object ({ name: ‘toto’ }).

If any variable keeps **strong reference** on the object, the object will not be a garbage collector, but if there are only variables that keep **weak reference** on the object, it will be removed by garbage collector.

Some variable types have a weak reference on an object, this is the case for **Weakmap**.

### Weakmap

A weakmap is an additional data storage, it can allow us to extend an object from outside (third party lib) or sealed object without inferring garbage collector ! Or create a cache function smartly !

Don’t panic I will explain and show what it means ! Before we will compare map and weakmap.

### Map vs Weakmap

With map the object occupies memory and may not be garbage collected. Map has **strong** reference on objet.

```js
let obj = { name: 'toto' }
let mapObj = new Map()
mapObj.set(obj, 'any value')

obj = null
mapObj.size() // 1
```

Weakmap is totally different, it doesn’t prevent garbage-collection of key objects.

First rule, weakmap accepts only `object as key`, secondly it keeps only weak reference on object.

```js
let obj = { name: 'toto' }
let weakmapObj = new WeakMap()
weakmapObj.set(obj, 'any value')

obj = null
weakmapObj .size() // 0
```

Object is removed by garbage collector since weakmap has only **weak reference** on the object { name: ‘toto’ } and this object has no longer strong reference ! (only the variable obj has keep reference on it)

## When use this ?

As you can see, Weakmap is strong (yes it's a joke) but it can be use everytime, it can be used in a few situation.

**Cache Function**

```js
const cache = new WeakMap() 

const process = function (obj) { 
    // If the input is not already cached 
    if (!cache.has(obj)) { 
        // Imagine a function that need a lot of memory/ressource 
        // We don't want to re-execute bigOperation function
        // if the input is the same ! 
        const result = bigOperation(obj) 
        // So we execute the function one time and
        // we store the result in cache ! 
        cache.set(obj, result) 
    } 
    return cache.get(obj) 
} 

let obj = { /* any object */ } 
// first time we don't have this input as cache, so we will put into 
const firstResult = process(obj) 
// second time we don't need to execute the big function, 
// just need to exctract the result in cache 
const secondeResult = process(obj) 
// the original object will be removed from weakmap ! 
obj = null 
```
With a map, this cache function should have kept obj in memory !
It can lead to memory leaks !

Leak memory can be created when we keep reference on an unused object, so if you don’t use any more objects, remove any variable reference on it !

⚠️ We cannot use `.keys() / .values() / .entries()` with weakmap since we don’t know when the garbage collector will remove the object !

**Last exemple**

Counter of visits dynamic without leak memory

```js
// Counter of visits
let visitsCountMap = new WeakMap()

// increase the visits count
function countUser(user) {
  const count = visitsCountMap.get(user) || 0
  visitsCountMap.set(user, count + 1)
}

let toto = { name: "toto" }

countUser(toto) // count his visits

// later toto leaves us
toto = null
```

*Note: this article is inspired by https://javascript.info/weakmap-weakset*

---

I hope you like this reading!

🎁 You can get my new book `Underrated skills in javascript, make the difference` for FREE if you follow me on [Twitter](https://twitter.com/code__oz) and MP me 😁

Or get it [HERE](https://codeoz.gumroad.com/l/RXLYp)

🎁 [MY NEWSLETTER](https://www.getrevue.co/profile/code__oz)

☕️ You can [SUPPORT MY WORKS](https://www.buymeacoffee.com/CodeoZ) 🙏

🏃‍♂️ You can follow me on 👇

🕊 Twitter : [https://twitter.com/code__oz](https://twitter.com/code__oz)

👨‍💻 Github: https://github.com/Code-Oz

And you can mark 🔖 this article!