JavaScript Maps and Sets

Store unique values and keyed data with Set and Map, and hold weak references with WeakMap.

TL;DR

  1. Use Set to store unique value collections and eliminate duplicates.
  2. Use Map to match key-value pairs using any key type.
  3. Query size and iterate directly using standard for-of loops.

Set Basics

    Set initialization

    Creates a new Set from an iterable, automatically filtering out duplicate values.

    const numbers = new Set([1, 2, 2, 3]);
    console.log(numbers); // Set { 1, 2, 3 }
    add()

    Adds a new unique value to the Set collection and returns the Set.

    const colors = new Set();
    colors.add("red").add("blue");
    has()

    Checks if a specific value exists in the Set using constant time lookup.

    const exists = colors.has("red"); // true
    delete() and clear()

    Removes individual items or deletes all elements from the Set collection.

    colors.delete("red");
    colors.clear();

Map Basics

    Map initialization

    Creates a Map storing key-value pairs, maintaining insertion order of keys.

    const config = new Map([
      ["timeout", 5000],
      ["retries", 3]
    ]);
    set()

    Inserts or updates a value for a specific key in the Map.

    const user = new Map();
    user.set("name", "Alice");
    get()

    Retrieves the value associated with a specific key, returning undefined if missing.

    const timeout = config.get("timeout"); // 5000
    has() check

    Verifies if a key is present in the Map collection without reading it.

    const hasKey = config.has("timeout"); // true

Map vs Object

    Key types

    Map allows objects and functions as keys, whereas objects coerce keys to strings.

    const map = new Map();
    const keyObj = { id: 1 };
    map.set(keyObj, "metadata");
    console.log(map.get(keyObj)); // "metadata"
    Size properties

    Map counts elements directly via size, whereas objects require key array length.

    const map = new Map([["a", 1]]);
    console.log(map.size); // 1
    const obj = { a: 1 };
    console.log(Object.keys(obj).length); // 1

Iteration and Conversion

    Set iteration

    Loops through Set values directly using a standard for-of loop.

    const numbers = new Set([1, 2, 3]);
    for (const num of numbers) {
      console.log(num);
    }
    Map iteration

    Destructures entries into key-value pairs during iteration loops.

    const user = new Map([["name", "Alice"]]);
    for (const [k, v] of user) {
      console.log(k, v);
    }
    Spread conversions

    Converts collection elements back into standard arrays using the spread operator.

    const set = new Set([1, 2]);
    const arr = [...set]; // [1, 2]

What WeakMap Is

    WeakMap key values

    Stores key-value entries where keys are object references.

    const cache = new WeakMap();
    const user = { id: 1 };
    cache.set(user, { clicks: 3 });
    Weak references

    Allows garbage collection of key objects when references disappear.

    let el = document.querySelector("#widget");
    cache.set(el, { clicks: 0 });
    el = null; // entry can be collected now
    Key constraints

    Requires object keys, throwing errors when primitives are passed.

    // cache.set("key", 1); // TypeError

Tips

  1. Deduplicate an array instantly by wrapping it in a Set and spreading it back.
  2. Initialize a new Map directly from objects using the static Object.entries() conversion method.

Warnings

  1. Remember that object keys in Map collections are compared using strict reference identity matches.
  2. Standard JSON.stringify() serialization does not natively support Set or Map collections.

In Practice

FAQ