On this page

Maps in JavaScript

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

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​

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}`;

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Date

Next

Sets