javascriptweakmap

How to update a value of a existing key in WeakMap?


I can't find any example on MDN. I came up with this,

const simpleMap = new WeakMap()

const simpleObject = {};

simpleMap.set(simpleObject, "A Value");

if(simpleMap.has(simpleObject)) {
  simpleMap.set(simpleObject, "A New Value");
 }

Is this way correct or shall I delete the key first before doing this?


Solution

  • You could update directly.

    const simpleMap = new WeakMap()
    
    const simpleObject = {};
    
    simpleMap.set(simpleObject, "A Value");
    
    if (simpleMap.has(simpleObject)) {
        simpleMap.set(simpleObject, "A New Value");
    }
    
    console.log(simpleMap.get(simpleObject));