Find things by name, dedup without hand-written loops: Map and Set, explained plainly
The menu is a Map keyed by dish number, ordered dishes live in a Set, and button state sits in a WeakMap. This guide follows MDN's Map, Set, and WeakMap references: insertion order, any-value keys, the Map-vs-object table, the property-syntax trap, cloning and merging, groupBy, dedup, set operations, and when to reach for WeakMap.

First, the boundaries. The site already has “Stop writing for loops by hand: array methods”, about how to filter, transform, and collect arrays; “Stop dotting through properties one by one: destructuring”, about pulling several values out of objects and arrays at once; and “The page is a tree: DOM querying and traversal”, about finding nodes in the page. This guide covers none of those. It covers two things: what to store things in when there are many of them and you need to find one by name, and what to store them in when nothing may appear twice. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. This time it is about how its order page keeps track of things: the menu looked up by dish number, dishes a customer already ordered that must not be ordered twice, and the most-ordered dishes listed first. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about Map and Set syntax and behavior comes from three MDN reference pages — “Map”, “Set”, and “WeakMap”. The sources are listed in this article's meta information and evidence record. The examples in the docs — the contacts book, three people's phone numbers, the union of two sets of numbers, remembering whether a button was clicked — are the docs' own examples, not real services. By the end of this guide you should be able to do three things: reach for Map when you see “find by name” and Set when you see “no duplicates”; know when to use an object and when to use a Map; and know what a WeakMap is for and when not to use one.
Step 1: A Map is a ledger for finding things by name
A Map is a collection of key-value pairs — a ledger where every row has a key and a value, and you find the value by its key. MDN's opening example walks through the whole basic routine: new Map() opens an empty ledger; map.set("a", 1), map.set("b", 2), map.set("c", 3) write three rows; map.get("a") returns 1; setting the same key again with map.set("a", 97) does not add a row — the key still occupies one row, and the value becomes 97, so the ledger still has 3 rows; map.size is 3; map.delete("b") removes a row and size becomes 2. Remember three things: a key occurs only once in the ledger, setting it again changes the value rather than adding a row; get on a missing key returns undefined; and size tells you how many rows there are at a glance. The cafe order page keeps its menu exactly this way: one new Map(), dish numbers as keys and dish information as values, so taking an order is one map.get(number) call instead of flipping through all 24 dishes from the top. Remember the rule: to find things by name, use a Map.
Step 2: The order inside a Map is the order you put things in
A Map makes one very practical promise: it iterates in insertion order. A for...of loop over a Map hands you a two-member array on each round — key first, then value. keys() gives only keys, values() only values, entries() gives key-value pairs, and all three return iterators in insertion order. The forEach callback also runs in insertion order, but watch its argument order: value first, then key — the opposite of for...of, so mixing them up swaps key and value. MDN's example sets 0 to “zero” and 1 to “one” first, then prints “0 = zero” and “1 = one” with for...of, in exactly the order they went in. The cafe order page leans on this to sort “most ordered”: every time a customer orders a dish, its key is deleted and set again, so it moves to the end of the ledger, and reading the ledger from the start gives the dishes in most-recently-ordered order. Remember the rule: when order matters, use a Map — a Map's order is the order you put things in.
Step 3: A Map's keys can be anything, but an object key only matches “the same one”
This is the biggest difference between a Map and a plain object. An object's keys can only be strings or Symbols; a Map's keys can be any value — strings, numbers, objects, functions. MDN's example uses three different keys: the string “a string”, an empty object, and an arrow function, each stored fine, with size 3. But object keys are compared by reference, not by shape: myMap.get("a string") finds its value, because the two “a string” values are the same string; myMap.get({}) finds nothing, because the newly written empty object is not the same object that was stored, even though it looks identical. MDN also covers a counterintuitive point: NaN works as a key, and works well. Everybody knows NaN is not equal to NaN, but Map compares with the SameValueZero algorithm, in which NaN and NaN count as the same — so after myMap.set(NaN, "not a number"), a different NaN computed elsewhere still gets the value back. The cafe order page uses object keys for “find the order by table”: the table object itself is the key and the order is the value, so changing tables just means changing keys, with no need to invent a number string for every table. Remember the rule: for object keys, what counts is whether it is the same object, not whether it looks alike.
Step 4: Map versus object, in six places where they differ
MDN lines Map and the plain object up in one table, and the conclusion is that objects were used as ledgers only because there was no better built-in option — now that Map exists, most “find by name” jobs belong to Map. First, accidental keys: a Map contains nothing by default, only what you explicitly put into it; an object has a prototype with ready-made keys that can collide with your own if you are not careful. Second, security: a Map is safe to use with user-provided keys and values; setting user-provided key-value pairs on an object may allow an attacker to override the object's prototype, leading to prototype pollution attacks. Third, key types: a Map's keys can be any value, while an object's keys must be a String or a Symbol. Fourth, key order: a Map walks in straightforward insertion order; an object's key order has always been complex, and MDN advises against relying on it. Fifth, size: a Map has a ready-made size property; counting an object's entries means calling Object.keys first and counting its length — roundabout and slower. Sixth, iteration: a Map is directly iterable with for...of; an object is not iterable by default and has to borrow Object.keys or Object.entries. Objects still beat Map in two places: serializing to JSON is natively supported, while Map has no native support; and an object literal is quicker to write. The cafe order page's rule is: fixed configuration data goes in an object; keys that arrive at runtime, counts that change, and order that matters all go in a Map. Remember the rule: if the keys arrive at runtime, use a Map; only fixed configuration belongs in an object.
Step 5: Do not stuff things into a Map with property syntax — it is fake
This is a pitfall MDN gives its own section. Setting a property on a Map object is legal syntax — wrongMap["bla"] = "blaa" raises no error, and printing the map even shows bla hanging off it — but it has nothing to do with the Map's ledger: wrongMap.has("bla") is false, wrongMap.delete("bla") is false, and size does not grow. Property syntax walks the plain-object road, while the set method walks the Map ledger; the two keep separate books. The correct way is always the set method: contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" }), after which contacts.has("Jessie") is true, contacts.get("Hilary") is undefined, contacts.delete("Raymond") is false and delete("Jessie") is true, and size drops from 2 to 1. The cafe order page once had someone write it the wrong way: map["new dish"] = dish, and then map.get("new dish") was undefined forever at order time — it took half a day to discover the dish had never entered the ledger at all. Remember the rule: put things into a Map only with set — property syntax is fake.
Step 6: A Map can come from an array and go back to one; when merging, the later one wins
Moving between Map and array is smooth. Pass a two-dimensional array to new Map and a ledger is built in one go: new Map([["key1", "value1"], ["key2", "value2"]]), and map.get("key1") is “value1”. Going back, Array.from(myMap) or [...myMap] turns the ledger into a two-dimensional array again. Cloning works the same way: new Map(original) is a new ledger, clone.get(1) is “one”, and original and clone are not the same object. But MDN warns that only the ledger itself is cloned — the data inside is not, so it is only a shallow copy: change an object inside, and both ledgers see the change. Merging two ledgers is the same spread-and-rebuild: new Map([...first, ...second]), and when a key repeats, the later ledger wins. MDN's example has 1 mapped to “one” in the first ledger and to “uno” in the second, and the merged ledger maps 1 to “uno”; adding one more [1, "un"] makes it “un”. The cafe order page merges two branches' menus exactly this way: the main branch's menu first, the branch menu second, and a dish listed in both takes the branch's version. Remember the rule: swap between Map and array with spread syntax, and when merging, the later one wins.
Step 7: Learn two new method names first: groupBy and getOrInsert
Two more Map methods are worth knowing by name first, without mastering them right away. Map.groupBy groups elements by a callback: give it an iterable and a callback, and it returns a Map whose keys are the distinct values the callback returned and whose values are the arrays of elements in each group. getOrInsert is “fill it in if it is missing”: get a value by key, and if it is there return it; if not, insert a row with a given default value and return the inserted value. getOrInsertComputed does the same, but computes the default from a callback when the key is missing. The cafe order page finds groupBy perfect for “count dishes by category”: group the 24 dishes by category and the ledger holds how many hot dishes, cold dishes, and drinks there are. And “keep a tab per table” uses getOrInsert: the first order from a table creates an empty order first, then dishes are added into it. Remember the rule: to group things, look for groupBy; for “fill it in if it is missing”, look for getOrInsert.
Step 8: A Set is a basket that holds only one of each thing
A Set is a collection of values where each value may occur only once — adding it a second time adds nothing. MDN's opening example runs: mySet1.add(1) makes one, add(5) makes two, add(5) again is still two, add("some text") makes three; adding an object o makes four, and adding another { a: 1, b: 2 } that looks identical makes five, because the two objects are not the same reference; has(1) is true, has(3) is false, size is 5; delete(5) leaves size 4; and adding 5 back puts it at the end of the basket, not back in its old place. A Set also walks in insertion order: for...of, keys(), values(), entries(), and forEach all follow it, and entries() hands back [value, value] pairs because in a Set the key is the value itself. The cafe order page uses a Set to record “dishes this table has already ordered”: order the same dish twice and the basket still holds one copy, and counting size tells you how many different dishes were ordered. Remember the rule: when you want only one of each, use a Set.
Step 9: Deduplication is Set's smoothest trick
The most famous Set trick is deduplicating an array in a single line: [...new Set(numbers)]. MDN's example is a run of numbers with repeats — 2, 13, 4, 4, 2, 13, 13, 4, 4, 5, 5, 6, 6, 7, 5, 32, 13, 4, 5 — and after dedup it is 2, 13, 4, 5, 6, 7, 32, in the order each value first appeared. A string can go straight into a Set too: new Set("Firefox") holds 7 letters, because capital F and lowercase f count as two; new Set("firefox") holds 6, because lowercase f appears twice and only one copy stays. Going back, [...mySet] or Array.from(mySet) turns a Set into an array again. The cafe order page writes “which categories did the customer order from” this way: throw every dish's category into a Set, spread it back into an array, and the number of categories on the menu is obvious at a glance. Remember the rule: to dedup an array, think new Set first.
Step 10: Set does set math — no hand-written loops for union and intersection
Set also does the set operations from mathematics, and MDN gives seven methods at once. union is the union: keep everything either side has. intersection is the intersection: keep only what both sides have. difference is the difference: keep only what this side has and the other does not. symmetricDifference is the symmetric difference: keep only what exactly one side has, dropping what both have. isSubsetOf asks whether this set is a subset, isSupersetOf whether it is a superset, and isDisjointFrom whether the two have nothing in common — the last three only answer yes or no. MDN's example takes a as the set {1, 2, 3} and b as a Map with keys 1, 2, 4, and a.union(b) gives the four-element set {1, 2, 3, 4}. Two things to note: these methods require the thing they are called on to be an actual Set instance, but the argument only needs to be set-like — an object with a size property, a has() method, and a keys() method — and a Map qualifies. An array does not qualify, because it has no has() method or size property, and its keys() method produces indices instead of elements. The cafe order page uses union for “two tables combining their orders”: each table's dishes merged together are the combined bill; and difference for “ordered at this table but not that one”. Remember the rule: for set math, use Set's seven methods, and the argument only needs to be set-like.
Step 11: Set and array look things up at different speeds
When to use a Set and when to use an array has a practical dividing line from MDN. The has method checks whether a value is in the basket using an approach that is, on average, quicker than testing most of the elements previously added — in particular, on average faster than Array.prototype.includes when the array is long. Arrays have their own territory: taking things by index, sorting, turning into JSON, and chaining array methods all feel more natural on an array. One more thing: a Set has no indices, so taking the nth element means spreading it into an array first. The cafe order page's rule is: if the only question is “is it in there” or “is there a duplicate”, use a Set; if you need indices, sorting, or something to send to the server, use an array. Remember the rule: use Set to check membership, use an array for order and indices.
Step 12: A WeakMap is a ledger where things leave when their owner leaves
A WeakMap is a weaker version of Map — weak in that it does not prevent garbage collection. Its keys must be garbage-collectable, meaning objects and non-registered symbols; ordinary numbers and strings cannot be keys. Object keys are still compared by reference. Unlike Map, a WeakMap has no size, no keys, no clear, and cannot be enumerated. MDN puts it plainly: because a WeakMap does not allow observing the liveness of its keys, its keys are not enumerable — there is no method to obtain a list of the keys, and if there were, the list would depend on the state of garbage collection. If you want a list of keys, use a Map. Its use is to attach data to an object that is only valuable while the object is still alive: once nobody wants the object any more, the data is collected with it and never leaks. MDN's button example is exactly this: remembering whether each button was clicked, kept in a WeakMap, so that when a button is removed from the page its record is automatically garbage-collected with it. Hanging the same flag on the button itself as a property would let other code overwrite it and would make it show up in Object.keys. MDN also gives a caching example: store an incoming object together with its computed result in a WeakMap, and the next time the same object arrives, return the cached result without computing again. The cafe order page records “whether each dish button was clicked” this way: delete the button and the record goes with it, with no manual cleanup. Remember the rule: if data matters only while its object is alive, use a WeakMap; if you need to count or list, use a Map.
Step 13: Five questions to pick the right container — stop guessing
Finally, the choice comes down to five questions. First: do you need to find things by name? If yes, choose between an object and a Map — keys that arrive at runtime, counts that change, and order that matters mean Map; fixed configuration means an object. Second: may things repeat? If not, use a Set. Third: do you need indices, sorting, or JSON? If yes, use an array. Fourth: does the data matter only while some object is alive? If yes, use a WeakMap. Fifth: do you need to list all the keys? If yes, do not use a WeakMap — use a Map. The cafe order page splits by these five questions: the menu in a Map, ordered dishes in a Set, the order list in an array, button state in a WeakMap. Remember the rule: ask the questions first, then pick the container — do not write the code first and wonder where to put it afterwards.
Checklist: run through this list when your Map and Set are written
The chart below shows the causes of 120 lookup and dedup mistakes in one month on the fictional Greenstone Cafe order page: using an object as a dictionary, with keys colliding with the prototype or being treated as strings, 30 times (25.0%); checking membership with Array includes, one element at a time, slowing down as things grew, 24 times (20.0%); dedup with a hand-written loop that missed cases, 22 times (18.3%); comparing object keys by value, assuming look-alikes were the same, 18 times (15.0%); using a Map like a plain object, stuffing things in with property syntax, 14 times (11.7%); and forgetting to spread a Set back into an array after using it, 12 times (10.0%). 30 + 24 + 22 + 18 + 14 + 12 = 120, and the percentages add up to 100.0%. The numbers are invented examples; the lessons are real, and the largest category is exactly the problem Map exists to solve — using an object as a dictionary. When your own Map and Set are written, run through this list: are lookups by name in a Map or an object, and do the keys arrive at runtime; when the same key is set twice, do you know it changes the value rather than adding a row; are you reading a Map with get or with property syntax; do object keys match by reference or by looks, and did you fetch an old object with a new one; where order matters, are you relying on Map's insertion order; is dedup done with new Set or a hand-written loop; are set operations done with Set's seven methods or your own loops; are membership checks done with has or with includes; did you try to count size or list keys in a WeakMap; and before picking a container, did you ask the five questions. When all ten pass, the Map and Set are written right.
Comments (0)
Sources
Related articles
localStorage only stores strings and has no indexes. IndexedDB is a real database in the browser: structured data, far larger capacity, indexes, and transactions. Following MDN's Using IndexedDB, IDBDatabase, and IDBObjectStore: the five-step routine, opening, upgrades, keys, indexes, transactions, add versus put, get, cursors, ranges, and multi-tab upgrades.
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.
One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.