JavaScript Notes
Master the JavaScript Map data structure. Learn Map vs Object, set/get/has/delete/iteration, any-type keys, insertion order, WeakMap, and Map interview questions with real code examples.
A Map is a built-in JavaScript data structure that holds key-value pairs and remembers insertion order. Unlike plain objects, Map keys can be any type — strings, numbers, objects, functions, or even NaN.
💡 Key insight:Mapis a true hash map. It's optimised for frequent additions and removals, while plain{}objects are optimised for accessing properties by string key. For dynamic key-value work,Mapis almost always the better tool.
Creating a Map
3 87
Core Methods
const map = new Map();
// set — add or update
map.set("name", "Alice");
map.set("age", 28);
map.set("admin", true);
// get — retrieve by key
console.log(map.get("name")); // "Alice"
console.log(map.get("missing")); // undefined
// has — check existence
console.log(map.has("age")); // true
console.log(map.has("email")); // false
// delete — remove a key
map.delete("admin");
console.log(map.has("admin")); // false
// size — number of entries
console.log(map.size); // 2
// clear — remove all entries
map.clear();
console.log(map.size); // 0"Alice" undefined true false false 2 0
Any Type as a Key
"User metadata" "Function value" "The answer" "Not a number, but valid key" 4
With plain objects, all keys are coerced to strings.obj[42]andobj["42"]are the same key. Map uses strict equality (SameValueZero) for key comparison.
Iterating a Map
"apple: $1.2" "banana: $0.5" "cherry: $3.0" ["apple", "banana", "cherry"] [1.2, 0.5, 3] "apple → 1.2" "banana → 0.5" "cherry → 3"
Map Chaining
3000 [["host","localhost"],["port",3000],["debug",true],["timeout",5000]]
Converting Between Map and Object
2
{ x: 10, y: 20 }
[["x", 10], ["y", 20]]Practical: Frequency Counter
[["j",1],["a",2],["v",1],["s",1],["c",1],["r",1],["i",1],["p",1],["t",1]] ["a", 2]
Map vs Object Comparison
| Feature | Map | Plain Object {} |
|---|---|---|
| Key types | Any (objects, functions, NaN) | Strings and Symbols only |
| Insertion order | ✅ Guaranteed | ✅ (ES2015+, mostly) |
| Size property | .size (instant) | Object.keys(o).length (O(n)) |
| Iteration | Built-in iterable | Needs Object.entries() |
| Prototype pollution | ✅ None | ❌ Risk (inherited keys) |
| Performance (frequent add/delete) | ✅ Optimised | ❌ Not optimised |
| JSON serialisation | ❌ Not directly | ✅ JSON.stringify |
| Default keys | None | Inherited from Object.prototype |
When to Use Map
✅ Use Map when:
- Keys are not strings (objects, numbers, functions)
- You need guaranteed insertion order
- You frequently add/delete entries at runtime
- You need an easy
.sizecount - You want to avoid prototype pollution
✅ Use Object when:
- Working with JSON data (parse/stringify)
- Keys are only strings or symbols
- You need property shorthand or destructuring syntax
- Interfacing with APIs that expect plain objects
Common Mistakes
- Using
map[key]instead ofmap.get(key)— bracket notation bypasses the Map API and accesses object properties instead of Map entries. - Comparing object keys by value — Map uses reference equality for objects. Two objects
{id:1}and{id:1}are different keys. - Trying to JSON.stringify a Map directly —
JSON.stringify(map)returns{}. Convert to array or object first. - Forgetting
??when counting frequencies —map.get(key) + 1returnsNaNwhen the key doesn't exist yet (undefined + 1). Use?? 0.
Interview Questions
Q1. What is the difference between a Map and a plain JavaScript object?
Map allows any key type (including objects and functions); objects coerce keys to strings. Map guarantees insertion order, has a .size property, is iterable by default, and is free of prototype pollution. Use Map for dynamic key-value storage; use plain objects for JSON data and structured records.Q2. Can a Map have NaN as a key?
Yes. Map uses the SameValueZero algorithm for key comparison, which treatsNaN === NaNas true. Plain objects stringify keys, soNaNbecomes the string"NaN".
Q3. How do you get the number of entries in a Map?
Use the.sizeproperty — it's a computed property that returns the count in O(1). With plain objects, you needObject.keys(obj).length, which is O(n).
Q4. Does Map maintain insertion order?
Yes. Iterating a Map always yields entries in the order they were inserted. This is guaranteed by the specification, unlike plain objects where integer-like keys are sorted numerically.
Q5. How do you convert a Map to a plain object?
Object.fromEntries(map) — converts Map entries to an object. Works when all keys are strings.Q6. What is the time complexity of Map operations?
set,get,has, anddeleteare all O(1) average (hash map implementation). Iteration is O(n).
Q7. How would you implement memoization using a Map?
``js function memoize(fn) { const cache = new Map(); return function(...args) { const key = JSON.stringify(args); if (cache.has(key)) return cache.get(key); const result = fn(...args); cache.set(key, result); return result; }; } ``Key Takeaways
- Map is a true hash map: any key type, insertion-order iteration, O(1) operations.
- Always use
.get(),.set(),.has(),.delete()— never bracket notation. - Use
Object.fromEntries(map)to convert to plain object;new Map(Object.entries(obj))to convert from object. - Map excels when keys change dynamically, are non-strings, or you need
.sizewithout counting. WeakMapis the memory-safe variant — keys must be objects, and they're garbage-collected when no longer referenced.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Map — Key-Value Data Structure Complete Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, data, structures, map
Related JavaScript Master Course Topics