JavaScript Map and Set for Pythonistas (Summary)

Rosa’s season report now runs in JavaScript. garden-report.js prints the same fourteen lines as garden_report.py, from “Brook Street Community Garden: end of season 2026” to “Seed swap, section D: nothing yet”. It hands plot 3 to Dev Patel, member 214. Keep these JavaScript techniques handy when you port your next script built on dicts, Counters, or sets:

  • Keep number keys as numbers and in insertion order with a Map, update it with .set() and .delete(), and test for a key with .has().
  • Keep an object for a record’s named fields and a Map for a lookup keyed by data. Save the waiting list as JSON with JSON.stringify([...waiting]) and restore it with new Map(JSON.parse(text)).
  • Store counts in a Map with (entries.get(c) ?? 0) + 1, where Python’s Counter supplies the zero.
  • Group records with Object.groupBy() or Map.groupBy().
  • Combine Sets with .union(), .intersection(), and .difference(), and compare them with .isSubsetOf() and .isDisjointFrom().
  • Build a Map of Sets with .getOrInsert() where Python uses defaultdict(set) or setdefault(), and deep-copy it with structuredClone(), as copy.deepcopy() does.

Keep the JavaScript Habits and Drop the Python Ones

Before you pick a container, ask: Are the keys names you write or values you’re given? A plot’s holder is a name you write, so the plot stays an object. Member numbers come from the society’s list, so the waiting list is a Map.

Reading a missing key gives undefined, never a default, so put ?? 0 on every count that might be missing and ?? [] on every group that might be.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.