Map & Set

Published by Brayan K

Objects and arrays cover a lot of ground, but JavaScript has two purpose-built collections that do specific jobs better: Map for key/value pairs with any key type, and Set for collections of unique values.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Decide whether you need an association or membership

Use a Map when a key identifies a value you want to retrieve or update. Use a Set when the question is whether a value is present. A record with fixed named fields or an ordered list can still be an ordinary object or array; neither collection is an automatic upgrade for every task.

const stock = new Map([["A17", 3], ["B24", 5]]);
console.log(stock.get("A17"));
stock.set("A17", 7);
console.log(stock.size, stock.get("A17"));
console.log(stock.delete("B24"));
console.log(stock.delete("B24"));
console.log(stock.has("B24"), stock.size);

// ✅ Expected output:
// 3
// 2 7
// true
// false
// false 1

Set updates one entry for the same key; it does not append a second copy of that key. Delete reports whether an entry was removed. The size property counts entries; it is not an array length or a callable method.

const stock = new Map([["A17", 3]]);
console.log(stock.size());

// ✅ Expected error:
// TypeError: stock.size is not a function

Bracket properties are not Map entries

Map methods manage the collection. Bracket assignment manages an ordinary property on the Map object instead. Mixing these two stores can make a debugger show a property even though get and has cannot find a collection entry.

const stock = new Map();
stock["A17"] = 3;
console.log(stock.size, stock.has("A17"), stock.get("A17"));
stock.set("A17", 8);
console.log(stock["A17"], stock.get("A17"), stock.size);
stock.clear();
console.log(stock.size, stock["A17"]);

// ✅ Expected output:
// 0 false undefined
// 3 8 1
// 0 3

Clear removes collection entries; it does not delete unrelated ordinary properties. Use set, get and has consistently. Object Methods (keys, entries, assign, freeze) owns inspecting ordinary object properties.

Use has when undefined can be a stored value

Get returns undefined for a missing key, but undefined can also be the value of a present entry. A truthiness check is also wrong when a valid stored value is zero, false or an empty string. Membership and value are separate questions.

const settings = new Map([
  ["pending", undefined],
  ["attempts", 0],
  ["enabled", false]
]);
for (const key of ["pending", "missing", "attempts", "enabled"]) {
  console.log(key, settings.has(key), settings.get(key));
}

// ✅ Expected output:
// pending true undefined
// missing false undefined
// attempts true 0
// enabled true false

Use has to decide presence and get to read the value. Type Coercion (== vs ===) owns truthiness; a false-looking value should not silently become a missing-entry rule.

Key types and object identity are preserved

A numeric key and a string key are distinct. Object keys are matched by identity, so constructing another object with the same fields does not retrieve the first object’s entry. Changing a field on the original object does not change that identity.

const user = { id: 7 };
const labels = new Map([
  [7, "numeric"],
  ["7", "text"],
  [user, "original object"]
]);
console.log(labels.size);
console.log(labels.get(7), labels.get("7"));
console.log(labels.get({ id: 7 }));
user.id = 8;
console.log(labels.get(user));

// ✅ Expected output:
// 3
// numeric text
// undefined
// original object

Ordinary object property keys are strings or symbols; saying they are all strings misses symbols. A Map accepts other key types without converting them to property keys. Symbols & Well-Known Symbols owns symbol properties.

const values = new Map();
values.set(NaN, "first");
values.set(Number("not a number"), "updated");
values.set(-0, "negative");
values.set(0, "zero");
console.log(values.size);
console.log(values.get(NaN), values.get(-0));

// ✅ Expected output:
// 2
// updated zero

This equality rule is called SameValueZero: NaN matches NaN and positive and negative zero match, while distinct object references remain distinct. It is not a deep comparison of object contents.

Insertion order is not sorted order

A Map visits entries in the order their keys were inserted. Updating an existing key keeps its position. Deleting that key and inserting it again creates a new insertion at the end.

const values = new Map([["B24", 2], ["A17", 1]]);
values.set("B24", 9);
console.log(JSON.stringify([...values]));
values.delete("B24");
values.set("B24", 4);
console.log(JSON.stringify([...values]));
console.log(JSON.stringify([...values.keys()]));
console.log(JSON.stringify([...values.values()]));

// ✅ Expected output:
// [["B24",9],["A17",1]]
// [["A17",1],["B24",4]]
// ["A17","B24"]
// [1,4]

A for...of loop over a Map receives key/value pairs. Destructuring Assignment owns unpacking each pair; Iterators & Iterables owns how an iterator supplies them.

Set uniqueness depends on the same value rule

A Set accepts each distinct value once. Adding a present value does not grow it or move that value to the end. String case and whitespace are still part of the value; normalization is your application’s decision.

const tags = new Set(["js", "css", "js", "JS"]);
console.log(tags.size);
console.log(JSON.stringify([...tags]));
console.log(tags.has("js"), tags.has(" js "));
console.log(tags.delete("css"), tags.delete("css"));
console.log(JSON.stringify([...tags]));

// ✅ Expected output:
// 3
// ["js","css","JS"]
// true false
// true false
// ["js","JS"]
const original = { id: 1 };
const values = new Set([original, original, { id: 1 }]);
console.log(values.size);
console.log(values.has(original), values.has({ id: 1 }));
const special = new Set([NaN, NaN, -0, 0]);
console.log(special.size);

// ✅ Expected output:
// 2
// true false
// 2

If duplicates mean the same identifier, collect the identifiers or write an explicit identifier rule. Do not assume Set compares every field. A Set is useful for membership, but this lesson does not claim it wins every performance comparison.

Conversions can discard distinctions

Spreading a Map gives an array of entry pairs, and spreading a Set gives its values. Converting a Map to an ordinary object must turn its keys into object property keys. Two distinct Map keys can therefore collide during that conversion.

const values = new Map([[1, "number"], ["1", "string"]]);
const entries = [...values];
const record = Object.fromEntries(values);
console.log(values.size, entries.length);
console.log(Object.keys(record).length, record["1"]);
console.log(new Map(Object.entries(record)).size);

// ✅ Expected output:
// 2 2
// 1 string
// 1
const stock = new Map([["A17", 3], ["B24", 5]]);
console.log(JSON.stringify(stock));
const encoded = JSON.stringify([...stock]);
console.log(encoded);
const restored = new Map(JSON.parse(encoded));
console.log(restored.get("A17"), restored.size);

// ✅ Expected output:
// {}
// [["A17",3],["B24",5]]
// 3 2

The entry-array round trip works for these string keys and numeric values. It does not promise to preserve object identity, symbols, undefined or every possible key/value through JSON. Deep Dive into JSON, Parsing & Serialization owns serialization contracts and validation.

Copies still share referenced values

Constructing a new Map from another Map creates a new collection, but it does not clone object values or object keys. Changes to the collection and changes to a shared object are different operations.

const original = new Map([["A17", { quantity: 3 }]]);
const copied = new Map(original);
copied.get("A17").quantity = 9;
console.log(original.get("A17").quantity);
copied.set("A17", { quantity: 4 });
console.log(original.get("A17").quantity, copied.get("A17").quantity);
console.log(original === copied);

// ✅ Expected output:
// 9
// 9 4
// false

A new Set built from an old Set similarly retains the same object references. Spread & Rest Operators owns the shallow-copy model; collection construction is not a deep-cloning operation.

Use Set membership to express a selection

When one collection names acceptable values, use has to make that membership rule explicit. This example keeps values from the first set that also occur in the second, preserving the first set’s iteration order.

const requested = new Set(["js", "css", "html"]);
const available = new Set(["html", "js"]);
const shared = [...requested].filter(tag => available.has(tag));
const missing = [...requested].filter(tag => !available.has(tag));
console.log(JSON.stringify(shared));
console.log(JSON.stringify(missing));

// ✅ Expected output:
// ["js","html"]
// ["css"]

This composition uses familiar operations rather than requiring newer Set-composition methods. map, filter & reduce owns the callback selection rule.

Complete a membership check and an insertion

Record each page identifier once. Fill the two method names using the literal hints. Reading membership before and after insertion helps distinguish the query from the mutation.

const visited = new Set(["home"]);
console.log(visited.___("guide"));
visited.___("guide");
visited.add("guide");
console.log(visited.has("guide"), visited.size);
// 👉 replace ___ with has
// 👉 replace ___ with add

// ✅ Expected output:
// false
// true 2

Count requested items without changing their identifiers

Write countRequests for an array of string item identifiers. Return a Map whose values count how often each exact identifier occurs. Preserve first-occurrence order, keep case differences distinct and return an empty Map for empty input. Do not change the input array. Print the resulting entry pairs and the empty-input size.

function countRequests(ids) {
  const counts = new Map();
  for (const id of ids) {
    const previous = counts.has(id) ? counts.get(id) : 0;
    counts.set(id, previous + 1);
  }
  return counts;
}
const requests = ["A17", "B24", "A17", "a17", "B24", "A17"];
console.log(JSON.stringify([...countRequests(requests)]));
console.log(countRequests([]).size);
console.log(JSON.stringify(requests));

// ✅ Expected output:
// [["A17",3],["B24",2],["a17",1]]
// 0
// ["A17","B24","A17","a17","B24","A17"]

The contract treats identifiers as exact strings. If a product needs case-insensitive identifiers, decide and document a normalization rule before counting. Map does not make that decision for you.

References: MDN documents Map and Set, including key equality and insertion order.

Practice quiz

What does this complete program print? const m = new Map(); m["a"] = 4; console.log(m.size, m.get("a"), m["a"]);

  • 0 undefined 4
  • 1 4 4
  • 1 undefined 4
  • 0 4 undefined

Answer: 0 undefined 4. Bracket assignment creates an ordinary property, not a Map entry.

What does this complete program print? const m = new Map([["a", undefined]]); console.log(m.has("a"), m.has("b"), m.get("a") === m.get("b"));

  • false false true
  • true false true
  • true false false
  • true true true

Answer: true false true. Get alone cannot distinguish the stored undefined from a missing key; has can.

What does this complete program print? const key = { id: 1 }; const m = new Map([[key, "found"]]); console.log(m.get({ id: 1 }), m.get(key));

  • found found
  • found undefined
  • undefined found
  • undefined undefined

Answer: undefined found. Only the original object reference identifies the stored key.

What does this complete program print? const m = new Map([["b", 1], ["a", 2]]); m.set("b", 9); console.log(JSON.stringify([...m.keys()]));

  • ["a","b"]
  • ["b","a","b"]
  • ["b"]
  • ["b","a"]

Answer: ["b","a"]. Updating an existing key preserves its insertion position.

What does this complete program print? console.log(new Set([1, "1", NaN, NaN, -0, 0]).size);

  • 4
  • 6
  • 5
  • 3

Answer: 4. Numeric and string one differ, NaN is one value, and signed zeros share one value.

What does this complete program print? const item = { id: 1 }; console.log(new Set([item, item, { id: 1 }]).size);

  • 1
  • 2
  • 3
  • 0

Answer: 2. The repeated reference is one value, while the separately created object is another.

What does this complete program print? const m = new Map([[1, "number"], ["1", "string"]]); const record = Object.fromEntries(m); console.log(m.size, Object.keys(record).length, record["1"]);

  • 2 2 string
  • 1 1 number
  • 2 1 string
  • 2 1 number

Answer: 2 1 string. Both Map keys become the same string property key, and the later entry supplies its value.

What does this complete program print? const first = new Map([["a", { count: 1 }]]); const second = new Map(first); second.get("a").count = 5; console.log(first.get("a").count, first === second);

  • 1 false
  • 5 true
  • 1 true
  • 5 false

Answer: 5 false. The collection is copied but the nested value remains the same object reference.

Continue this course

Related lessons