Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Map and Set

Besides objects and arrays, JavaScript has two more built-in collections. Map is a "key → value" dictionary, and Set is a group of values without duplicates. A collection is any value that holds many other values.

Map: creating and reading

A Map is created with new Map(). The set() method puts a value under a key, and get() reads it back:

const prices = new Map();
 
prices.set('tea', 5);
 
console.log(prices.get('tea')); // 5

If the key is missing, get() returns undefined.

Map methods

The size property holds the number of entries, has() checks for a key, and delete() removes an entry. Initial data can be passed right away as an array of pairs:

const prices = new Map([
  ['tea', 5],
  ['coffee', 12],
]);
 
prices.delete('tea');
 
console.log(prices.size);          // 1
console.log(prices.has('coffee')); // true

Iterating over a Map

A Map is iterated with for...of. Each step yields a [key, value] pair, and entries come in the order they were added:

const prices = new Map([
  ['tea', 5],
  ['coffee', 12],
]);
 
for (const [title, price] of prices) {
  console.log(`${title}: $${price}`);
}
// tea: $5
// coffee: $12

The main difference from an object is that a Map key can be a value of any type: a number, an object, even a function. A plain object's keys are always strings.

Set: unique values

A Set stores each value only once. The add() method adds a value, and adding it again changes nothing:

const tags = new Set();
 
tags.add('js');
tags.add('css');
tags.add('js');
 
console.log(tags.size); // 2

Like Map, a Set has has() and delete() methods.

Removing duplicates from an array

The most common trick with Set is removing duplicates from an array. Pass the array to new Set() and spread the result back into an array with ...:

const numbers = [1, 2, 2, 3, 1];
 
const unique = [...new Set(numbers)];
 
console.log(unique.join(', ')); // 1, 2, 3

Common mistake

You cannot write to a Map with square brackets as you would with a plain object. Such an assignment creates a property on the Map object itself, and no entry appears in the dictionary:

const prices = new Map();
 
prices['tea'] = 5;
 
console.log(prices.size);       // 0
console.log(prices.get('tea')); // undefined

Always use set() and get() with a Map.

Thanks for reading!

Donate to the site — we work hard for you.