Technology · JavaScript

JavaScript Set and Map

Work with collections using Set and Map, understand key differences, and common use cases.

TL;DR
  1. 01Use Set to store unique values and check membership quickly.
  2. 02Use Map for key-value pairs with any type as the key.
  3. 03Both are iterable with for-of and have size properties.

Set Basics

  • Create a Set to store unique values of any type.
    const numbers = new Set([1, 2, 2, 3, 3, 3]);
    console.log(numbers); // Set { 1, 2, 3 }
  • Use add() to insert values into the set.
    const colors = new Set();
    colors.add("red");
    colors.add("blue");
  • Use has() to check if a value exists in the set.
    colors.has("red");  // true
    colors.has("green"); // false
  • Use delete() to remove a value and clear() to empty the set.
    colors.delete("red");
    colors.clear();
  • Use size to get the number of unique values in the set.

Map Basics

  • Create a Map to store key-value pairs with any type of key.
    const user = new Map();
    user.set("name", "Alice");
    user.set("age", 30);
  • Use set() to add or update entries in the map.
    const config = new Map([
      ["timeout", 5000],
      ["retries", 3]
    ]);
  • Use get() to retrieve values by their key.
    config.get("timeout"); // 5000
  • Use has() to check if a key exists without retrieving the value.
    config.has("timeout"); // true
  • Use delete() and clear() to remove entries or empty the map.

Set vs Object

  • Set stores unique values, while object keys are always strings or symbols.
    const set = new Set([1, "1", 1]); // Set { 1, "1" }
    const obj = {};
    obj[1] = "number";
    obj["1"] = "string";
    // obj only has one key "1" with value "string"
  • Set uses has() for membership checking, objects use in operator.
  • Set automatically prevents duplicates, objects do not.
  • Use Set when you only care about unique values without keys.
  • Use Map or object when you need to associate values with keys.

Map vs Object

  • Map can use any type as a key, objects only use strings or symbols.
    const map = new Map();
    map.set({x: 1}, "object key");
    map.set(() => {}, "function key");
    
    const obj = {};
    obj[{x: 1}] = "converts key to string";
  • Map preserves insertion order, objects mostly do but with quirks.
  • Map has a size property, objects require Object.keys() to count.
  • Map is optimized for frequent additions and deletions.
    const cache = new Map();
    cache.set(userId, userData);
  • Use Map when keys are not strings or for better performance.

Iteration and Conversion

  • Iterate over a Set using for-of or forEach().
    const numbers = new Set([1, 2, 3]);
    for (const n of numbers) console.log(n);
    numbers.forEach(n => console.log(n));
  • Iterate over a Map with for-of to get [key, value] pairs.
    const user = new Map([["name", "Alice"], ["age", 30]]);
    for (const [key, value] of user) console.log(key, value);
  • Convert Set to Array using the spread operator.
    const arr = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]
  • Convert Map to Array of entries or use .entries(), .keys(), .values().
    const entries = [...user.entries()];
    const keys = [...user.keys()];
    const values = [...user.values()];

Tip: Use Set to remove duplicates from an array quickly with the spread operator: [...new Set(array)].

Warning: Map keys are compared by reference, not value, so new Map().set({}, 1).get({}) returns undefined since the objects are different.

JavaScript PromisesJavaScript String Methods