Skip to content

Maps in JavaScript

A Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

Creating a Map

You can create a Map using the new Map() syntax.

let map = new Map();
//or
const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

Setting, Getting, and Checking Values

The set method is used to set a key-value pair, get method is used to get the value by a key, and has method is used to check if a key exists.

map.set('name', 'John');  // sets the key 'name' with value 'John'
console.log(map.get('name'));  // outputs 'John'
console.log(map.has('name'));  // outputs true

Size and Clear

The size property returns the current number of entries, and clear method removes all entries.

console.log(map.size);  // outputs 1
map.clear();
console.log(map.size);  // outputs 0

Deleting a Value

The delete method removes a value by its key.

map.set('name', 'John');
map.delete('name');
console.log(map.has('name'));  // outputs false

Iterating Over a Map

You can use for...of loop to iterate over a Map. It returns key-value pairs in the insertion order.

map.set('name', 'John');
map.set('age', 30);

for (let [key, value] of map) {
    console.log(`${key}: ${value}`);
}
//to iterate over values only
for (let [_, value] of map) {
    console.log(value);
}
//to iterate keys only
for (let key of map.keys()) {}

Object vs Map

  • Keys of any type: While objects only allow strings and symbols to be keys, a Map allows any data type to be a key including functions, objects, and any primitive value.
  • Order: The Map object holds key-value pairs and remembers the original insertion order of the keys. On the other hand, the order of keys in an object is complex and doesn’t rely on the order of insertion.
  • Size: You can easily get the number of entries in a Map using the size property, while you have to manually count the number of properties in an Object.

Tuples as keys

Since JavaScript does not support tuples, like other languages do, one way to use tuples as keys it to convert tuples to a string and then use them as keys:

const key = `${i},${j}`;