Object vs map
Hey, what are some situations where you’d use a map over an object? To me, they’re essentially the same thing with map’s keys not only being limited to strings, but personally, I don’t see a need to put any other data type as a key?
I’d appreciate some insight, thanks in advance
7 Replies
a map maps between anything to anything, and makes it a lot easier and quicker to check if something exists in the map or not
you literally can map the
<html>
element to 55
an object can't do that: just strings to valuesah i see, but why may you want to do that? unless it's something very niche?
Aside from the fact that Map is faster for insertion and deletion, objects also have prototypal inheritance. The following code outputs "true":
The object should be empty, but it already has properties via prototypal inheritance, so you have to be careful when using the object to hold properties with certain names. Maps don't have this problem. The get() method will never return anything other than undefined from an empty Map regardless of the key provided.
yup, and with pojos you need to be careful because specific names have specific meaning
you can create one without a prototype by using
Object.create(null)
, but that's also very niche
also, sometimes it's nice to be able to map objects to something elseAlthough a Map can have keys of any type, and the type is preserved, it is important to be careful when using objects as keys, because objects use referential equality. The result is that you can set a value using an object key and attempting to get the value later may fail when using a different object that is structurally identical to the original object used to set the value. For example:
yes, because it's 2 different instances of objects
Ah okay got it, thanks everyone