Maps vs. Objects

Maps vs. Objects

Want to store data as key-value pairs? Maps & Objects are the possible solutions. Let's say you want to store information about a person

// Objects
const person = { name: 'Nauman', age: 30 }
person.age // 30

// Maps
const personUsingMap = new Map();
personUsingMap.set('name','Nauman');
personUsingMap.set('age', 30); 
personUsingMap.get('age') // 30

Differences

Possible Key Collision w/ Objects

Apart from the syntactical differences, there are a few things we need to understand. Check this out

person.toString() // '[object Object]'

But toString() doesn't exist on the person object above. Objects have prototypes, so they can contain keys which you by chance want to keep on your object as well.

Whereas with Map you only get what you actually put into it.

If you want to use Objects as Map and want to avoid this, You can create object with Object.create(null);

But that would also result in not being able to use default functionality! Which isnt' a best practice for working with objects in general

Key Types

One major difference is with Objects, the keys can either be Strings or Symbol. But Map has the edge on it that you can store anything as keys i.e array, objects, functions

// Objects
const person = {};
const array = [1,2,3]
person[array] = 'array'

for (let key in person)
  console.log(key instance of Array) // false

const pMap = new Map();
pMap.set(array, 'array');
for (let k of p.keys())
  console.log(k instanceof Array) // true

For objects, array would be stringified while this is not the case for Map.

Direct Assignment w/ Maps

Always use set(key, value) for Maps. If we don't, other Map operations like get, has, delete will fail.

const person = {};
person.name = 'nauman';
console.log(person); // {name: 'nauman'}

const map = new Map();
map['name'] = 'nauman';
map.get('name') // undefined

Further Reading

Check MDN for more.