const person = {
name: 'Hasnain',
age: 22,
profession: 'Web Developer',
};
const map = new Map(Object.entries(person));
console.log(map);
When and why to use Map over Object? 🤔
There are a lot of excellent people like you, with tons of knowledge out there writing awesome answers! Here is an amazing stackoverflow post I found that explains just that! 🎉🎊
You are lazy 🥴
I know you are lazy like me (every good developer should be), so I'd like to briefly describe the difference between Object and Map. With that information, be the judge of when to use which! 😎
According to Mozilla:
- A Map's key can be any value, including primitive types, objects and functions.
- You can use
for...of
loop to iterate Map in the insertion order, meaning what you first inserted will be the first element to show up in the loop and so on.- Just as Array have
length
property, Map comes with asize
property.- Performs better when a lot of insertion and removal operations are involved.
Top comments (3)
Do you know some use cases in which functions as keys of a
Map
would be relevant ?Doing that is less useful compared to passing objects as keys but not useless. Here is the best example I could come up with.
Here we just implemented a caching system where a function that does some heavy computation runs only once and we don't have to worry about giving them clever and unique keys.
Also, keep in mind that in JavaScript, functions are objects! You can even use Function constructor to instantiate functions. Probably, that's why you can pass functions as keys to
Map
.Oh, ok I got it .
Thanks for the example, it's helpful. 👍