panzerdp / dmitripavlutin.com-comments

7 stars 0 forks source link

maps-vs-plain-objects-javascript/ #121

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

When to Use Map instead of Plain JavaScript Object

Map complements plain objects. Map's main benefits over plain object is allowing keys of any type and any name.

https://dmitripavlutin.com/maps-vs-plain-objects-javascript/

iraqwarvet31 commented 3 years ago

Great article Dmitri!!

panzerdp commented 3 years ago

Great article Dmitri!!

Thanks @iraqwarvet31!

Rishabh3321 commented 2 years ago

I am curious about JS implements Map under the hood. Is it a BST or hashtable. How it is able to accept keys of anytype ?

gtarsia commented 1 year ago

Very concise, good demonstration of how objects are limited/unsafe.

jcampbell1710 commented 11 months ago

A lot comes down to where you want to trade-off. JS is not strongly typed and the Object is defined to work fine without typing. For example, you can use numbers as properties for an object and access them accordingly, without ambiguity.

x = { 1: 'hey', 2: 'there' };
console.log('x[1]=', x[1]);
console.log("x['2']=", x['2']);
console.log('x[2]=', x[2]);
// is this an array?
console.log('x[0]=', x[0])

results in

x[1]= hey
x['2']= there
x[2]= there
x[0]= undefined

I would not want to declare anything in this way, but if you need to use an object to store from an external source, it will be fine to use numbers.

Maps are excellent to have in the language, but objects are likely enough to cover most k/v mappings.