Sets & Maps

Store unique values with Set and keyed data with Map.

Syntaxnew Set([1, 2, 2]) new Map()

ES6 added two useful collection types:

  • Set β€” a collection of unique values. Adding a duplicate has no effect.
  • Map β€” key/value pairs where keys can be any type, with a reliable size and order.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Deduplicate an array of user-selected tags using a Set before saving them to the database.
  • Cache API responses in a Map keyed by URL so repeated requests return instantly.
  • Count how many times each word appears in a text string using a Map as a frequency table.

More examples

Set for unique values

Creates a Set from an array to remove duplicates, then spreads it back into an array.

Example Β· js
const rawTags = ["js", "css", "js", "html", "css"];
const unique = new Set(rawTags);
console.log([...unique]); // ["js", "css", "html"]

Map as a keyed cache

Uses a Map to cache results by URL so repeated calls skip the simulated fetch.

Example Β· js
const cache = new Map();
function fetchWithCache(url) {
  if (cache.has(url)) return cache.get(url);
  const data = `data for ${url}`; // simulated fetch
  cache.set(url, data);
  return data;
}
console.log(fetchWithCache("/api/users"));
console.log(fetchWithCache("/api/users")); // returns cached

Map as word frequency counter

Builds a frequency table using a Map where each word is a key and its count is the value.

Example Β· js
const words = ["the", "cat", "sat", "on", "the", "mat", "the"];
const freq = new Map();
for (const w of words) {
  freq.set(w, (freq.get(w) ?? 0) + 1);
}
console.log(freq.get("the")); // 3

Discussion

  • Be the first to comment on this lesson.
Sets & Maps β€” JavaScript | SoundsCode