Map, Set, JSON and storage
Map and Set are the right tools when keys are not strings or values must be unique, and JSON plus localStorage/sessionStorage is how data survives a page refresh. Each has a trap: object keys turn into strings, Sets compare objects by reference and storage keeps only strings.
17.1 The problem: an object as a key
- Normal object keys are always strings (or symbols).
- Using an object as a key converts it to the string "[object Object]".
- Both users became the same key, so Priya's 9 overwrote Rahul's 5.
JavaScript
const visits = {};const rahul = { id: 1 };const priya = { id: 2 }; visits[rahul] = 5;visits[priya] = 9; console.log(visits[rahul]);console.log(Object.keys(visits));Output
9[ '[object Object]' ]17.2 Fix: Map
- A Map key can be of any type, including a whole object.
- API: set, get, has, delete, size; iterate with for...of as [key, value].
- Keeps insertion order and is optimized for frequent adds and deletes.
JavaScript
const visits = new Map();const rahul = { id: 1 };const priya = { id: 2 }; visits.set(rahul, 5);visits.set(priya, 9); console.log(visits.get(rahul));console.log(visits.size, visits.has(priya)); visits.delete(priya);for (const [user, count] of visits) { console.log(user.id, count);}Output
52 true1 517.3 Set: only unique values
- new Set(array) removes duplicates automatically.
- has is a fast membership check; adding an existing value changes nothing.
- [...set] spreads it back into an array.
- New set methods like difference, union and intersection compare two sets.
JavaScript
const orders = ["UPI", "Card", "UPI", "COD"]; const methods = new Set(orders);console.log(methods.size);console.log(methods.has("COD")); methods.add("Card");console.log([...methods]); const online = new Set(["UPI", "Card"]);console.log(methods.difference(online));Output
3true[ 'UPI', 'Card', 'COD' ]Set(1) { 'COD' }17.4 WeakMap: object keys, auto cleanup
- Keys must be objects and are held weakly.
- When nothing else references the key object, the garbage collector can remove the object and its entry.
- So a WeakMap cannot be looped over or sized; used for caches and attaching extra data to objects.
JavaScript
const lastSeen = new WeakMap();let user = { id: 1 }; lastSeen.set(user, "10:30 AM");console.log(lastSeen.get(user));console.log(lastSeen.has(user)); user = null;Output
10:30 AMtrue17.5 Comparison: Object vs Map vs Set vs WeakMap
| Point | Object | Map | Set | WeakMap |
|---|---|---|---|---|
| Stores | key -> value | key -> value | Unique values | object key -> value |
| Key types | String, symbol | Any type | Any value | Objects only |
| Size | Object.keys(o).length | .size | .size | Not available |
| Iterable | Via Object.keys/entries | Yes, in insertion order | Yes | No |
| Best for | Fixed-shape records, JSON | Dynamic keys, frequent add/delete | Dedup, membership checks | Caches, metadata tied to objects |
17.6 JSON: object to string and back
JavaScript
const cart = { item: "Shoes", qty: 2 }; const text = JSON.stringify(cart);console.log(typeof text);console.log(text); const back = JSON.parse(text);console.log(back.qty + 1);Output
string{"item":"Shoes","qty":2}3- JSON.stringify -> text you can save or send; JSON.parse -> object again.
- JSON is not a perfect deep copy: a Date becomes a string, undefined keys and functions are dropped.
- Use structuredClone for a real deep copy (keeps Date as Date).
JavaScript
const order = { total: 499, placedAt: new Date(), coupon: undefined,}; const text = JSON.stringify(order);const copy = JSON.parse(text);console.log(typeof copy.placedAt);console.log("coupon" in copy); const clone = structuredClone(order);console.log(clone.placedAt instanceof Date);Output
stringfalsetrue17.7 localStorage and sessionStorage
- Step 1
1.Object in memory: [{ item: "Shoes", qty: 2 }]
- Step 2
2.JSON.stringify -> string
- Step 3
3.localStorage.setItem("cart", json) -> saved in the browser
- Step 4
4.Page refresh / next visit: localStorage.getItem("cart")
- Step 5
5.null on first visit -> fall back to []
- Step 6
6.Else JSON.parse (inside try/catch) -> object again
JavaScript
const cart = [{ item: "Shoes", qty: 2 }];const json = JSON.stringify(cart);localStorage.setItem("cart", json); const saved = localStorage.getItem("cart");const items = saved ? JSON.parse(saved) : [];console.log(items[0].item); const user = { name: "Rahul" };localStorage.setItem("user", user);console.log(localStorage.getItem("user")); sessionStorage.setItem("step", "2");console.log(sessionStorage.getItem("step"));Output
Shoes[object Object]2| Point | localStorage | sessionStorage |
|---|---|---|
| Lifetime | Stays after the browser is closed | Cleared when the tab is closed |
| Scope | All tabs of the same origin | Only that tab |
| Stores | Strings only | Strings only |
| API | setItem, getItem, removeItem, clear | Same |
17.8 Checkpoint: storage turns numbers into strings
JavaScript
localStorage.setItem("qty", 2);const qty = localStorage.getItem("qty");console.log(qty + 1);Output
21- getItem returns the string "2"; "2" + 1 concatenates to "21".
- Convert when reading: Number(qty) or JSON.parse.
17.9 Common mistakes
- Deduplicating objects with a Set: Set compares objects by reference, so two { id: 7 } stay. Use a Map keyed by id.
- Saving an object without JSON.stringify: you get back "[object Object]".
- JSON.parse on corrupt storage data without try/catch: it throws.
- Keeping passwords or login tokens in localStorage: any script on the page can read it.
JavaScript
const cart = [{ id: 7 }, { id: 7 }]; // Wrong: size 2 (compared by reference)const unique = new Set(cart);console.log(unique.size); // Right: size 1 (unique by id)const ids = new Map(cart.map(p => [p.id, p]));console.log(ids.size);17.10 Interview tips
- Object keys are strings or symbols; Map keys can be any type.
- Map keeps insertion order, has .size and is fast for frequent add/delete.
- WeakMap keys are weakly held, so entries are garbage collected with the object.
- Storage keeps only strings: stringify on save, parse in try/catch on load.
- Deep copy: structuredClone, not JSON (loses Date, undefined, functions).