FrontendDeveloper.in

ECMAScript question detail

Symbols as weakmap keys

Prior to ES2023, WeakMaps are only limited to allow objects as keys because objects are unique and cannot be re-created. Since symbols are the only primitives in ECMAScript that allows unique values, WeakMap API has been extended with symbols as keys instead of just using objects.

As an example, the usage of WeakMap with objects as keys prior to ES2023 looks like below

const weak = new WeakMap();
const objKey = { x:10 };

weak.set(objKey, "ES2023");
console.log(weak.get(objKey)); //ES2023

In ES2023, it is possible to use symbols as keys

const weak = new WeakMap();
const key = Symbol("ref");
weak.set(key, "ES2023");

console.log(weak.get(key)); //ES2023
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399