Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 168
Intermediate

JavaScript Set and Map

Master collection structures using Set and Map, understand key differences, and implement dynamic data lookups.

TL;DR

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

Tips

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

Warnings

  1. 01Remember that object keys in Map collections are compared using strict reference identity matches.
  2. 02Standard JSON.stringify() serialization does not natively support Set or Map collections.
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 169
Intermediate

JavaScript Set and Map

(continued)

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();
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 170
Intermediate

JavaScript Set and Map

(continued)

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
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 171
Intermediate

JavaScript Set and Map

(continued)

Set vs Object

  • Type constraints

    Set preserves variable types, while object keys are coerced to strings.

    const set = new Set([1, "1"]); // Set { 1, "1" }
    const obj = {};
    obj[1] = "num";
    obj["1"] = "str"; // overrides obj[1]
  • Unique storage

    Set filters duplicates natively, while objects require manual checks to prevent overwrite.

    const set = new Set([5, 5, 5]);
    console.log(set.size); // 1
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 172
Intermediate

JavaScript Set and Map

(continued)

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
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 173
Intermediate

JavaScript Set and Map

(continued)

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]
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 174
Intermediate

JavaScript Set and Map

(FAQ)

FAQ

Use the has() method, which performs instant lookup check queries. This method is much faster than checking arrays with includes(). Set checks take constant time regardless of size.

Yes, you can use any value including objects and arrays as keys in a Map. These keys are matched by reference. Two separate empty objects are treated as two distinct keys.

Use the array spread operator within the Set constructor. For example, write new Set([...setA, ...setB]). This automatically merges all elements while discarding duplicate entries.

Choose Map when keys are not strings or when insertion order must be preserved. A Map is also optimized for frequent additions and removals. Plain objects work better for simple static configs.

Convert entries by spreading the collection: [...myMap]. This returns an array of key-value pairs. To get only keys or values, use [...myMap.keys()] or [...myMap.values()].

Useful Cheatsheetsusefulcheatsheets.com
JavaScript Set and Map
Chapter 21 · Page 175
Intermediate

JavaScript Set and Map

(In Practice)
In Practice

Tracking Unique Logins and Frequencies

Processes raw login attempts to return unique user lists and trace login frequencies using Set and Map collections.

  1. 01Deduplicate the list of raw usernames by instantiating a Set collection.
  2. 02Spread the unique set items back into a standard username array.
  3. 03Create a new Map instance to log individual user frequency totals.
  4. 04Iterate through usernames, retrieving previous counts or defaulting to zero.
  5. 05Increment and update the login total for each user in the map.
function analyzeLogins(usernames) {
  const uniqueUsers = [...new Set(usernames)];

  const loginCounts = new Map();
  for (const user of usernames) {
    const count = loginCounts.get(user) ?? 0;
    loginCounts.set(user, count + 1);
  }

  return {
    uniqueUsers,
    loginCounts
  };
}
Takeaway

Use Set for instant value uniqueness checks and Map to associate dynamic values with reference keys.