Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a practical use of objects as keys within JS Map dataype?

I've recently been reading into Javascript's Map datatype (NOT the map() array method). MDN Reference

I've read and followed various tutorials/articles showing the similarities and differences between Maps, Arrays and 'standard' Objects. One unique property of Maps is that you can use any datatype as a key, including an Object.

There are many examples out there, such as this one from Tania Rascia

// Create an object
const objAsKey = { foo: 'bar' }

const map = new Map()

// Set this object as the key of a Map
map.set(objAsKey, 'What will happen?')

Here's the console output:

key: {foo: "bar"}
value: "What will happen?"

What I'm asking is, what is a benefit of this possibility? Why would I ever need to use an object as a key?

like image 448
Phil Blunt Avatar asked Feb 19 '20 09:02

Phil Blunt


1 Answers

From my tweets on the subject:

Say you have an object (like a DOM element) that you want to associate some data with, but you don't want to modify the object to add the data directly to it. So you use a Map with the object as key and your associated data as value.

typically, you'd want to use a WeakMap for this, so that if the original object goes away (garbage collected) the data is also released.

but a reason to use map instead of weakmap is that map is iterable and weakmap isn't.

so if you're willing to trade out that you need to do more manual work to manage the map entries (for cleaner garbage collection), then you get the ability to enumerate all the entries of the map, which can be useful in certain cases.

like image 59
Kyle Simpson Avatar answered Sep 28 '22 22:09

Kyle Simpson