SkillPilotAI

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 5

17.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 AMtrue

17.5 Comparison: Object vs Map vs Set vs WeakMap

PointObjectMapSetWeakMap
Storeskey -> valuekey -> valueUnique valuesobject key -> value
Key typesString, symbolAny typeAny valueObjects only
SizeObject.keys(o).length.size.sizeNot available
IterableVia Object.keys/entriesYes, in insertion orderYesNo
Best forFixed-shape records, JSONDynamic keys, frequent add/deleteDedup, membership checksCaches, 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
stringfalsetrue

17.7 localStorage and sessionStorage

Saving and loading data in browser storage
  1. 1.Object in memory: [{ item: "Shoes", qty: 2 }]

  2. 2.JSON.stringify -> string

  3. 3.localStorage.setItem("cart", json) -> saved in the browser

  4. 4.Page refresh / next visit: localStorage.getItem("cart")

  5. 5.null on first visit -> fall back to []

  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
PointlocalStoragesessionStorage
LifetimeStays after the browser is closedCleared when the tab is closed
ScopeAll tabs of the same originOnly that tab
StoresStrings onlyStrings only
APIsetItem, getItem, removeItem, clearSame

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).