JS Maps; the ugly step sibling of Objects

javascript, map, object

Main project image

Map objects are a collection of key-value pairs. They are iterable by insertion order and values are inserted by the set() method. Each key must be unique in the collection too.

Objects vs Maps

Objects have been used as Maps historically since both let you set keys to values, retrive values, delete keys and check if a key exists.

Here are a few differences between the two:

Key Types

Order of keys

Key Uniqueness

Iteration

Built-in Methods

Size Property

Setting a Map:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
map.set(3, 'value2')

console.log(map.get('key1')); // Output: value1
console.log(map.size); // Output: 3

map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
})

Setting an Object:

const obj = {
  key1: 'value1',
  key2: 'value2'
}

obj.key3 = 'value3'; // keys must be strings or symbols

console.log(obj.key1);

// iteration
Object.keys(obj).forEach(key => {
  console.log(`${key} : ${obj[key]}`)
})