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
ἔρως
ἔρως2d ago
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 values
snxxwyy
snxxwyy2d ago
ah i see, but why may you want to do that? unless it's something very niche?
Choo♚𝕂𝕚𝕟𝕘
Aside from the fact that Map is faster for insertion and deletion, objects also have prototypal inheritance. The following code outputs "true":
const obj = {};
console.log("toString" in obj);//true
const obj = {};
console.log("toString" in obj);//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.
ἔρως
ἔρως2d ago
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 else
Choo♚𝕂𝕚𝕟𝕘
Although 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:
const m = new Map();
m.set({number:42}, "forty two");
console.log(m.get({number:42}));//undefined
const m = new Map();
m.set({number:42}, "forty two");
console.log(m.get({number:42}));//undefined
ἔρως
ἔρως2d ago
yes, because it's 2 different instances of objects
snxxwyy
snxxwyy23h ago
Ah okay got it, thanks everyone
Want results from more Discord servers?
Add your server