JavaScript Map Object

Map

A Map stores key–value pairs where keys can be any type and maintains insertion order.
Syntax: const mp = new Map();

Map Use Cases
Use a Map when you need a fast, ordered key-value store where keys can be any type (objects, arrays, functions). It’s better than objects for frequent add/delete operations and when iteration order matters.

Map Methods

.set()

Adds a key-value pair to Map.
Syntax: mp.set(key, value)

.get()

Retrieves value for a given key.
Syntax: mp.get(key)

.has()

Checks whether a key exists.
Syntax: mp.has(key)

.size

Returns Map size (WeakMap has no size).
Syntax: mp.size

.delete()

Removes a specific key.
Syntax: mp.delete(key)

.clear()

Clears the entire Map.
Syntax: mp.clear()

.entries()

Returns an iterator of [key, value] pairs.
Syntax: mp.entries()

.forEach()

Iterates through key–value pairs.
Syntax: mp.forEach((val, key) => { ... })

WeakMap

WeakMap stores only object keys and allows automatic garbage collection with no iteration support.
Syntax: const wm = new WeakMap();

WeakMap Use Cases

Time Complexity and Space Complexity

Operation Map Set Explanation
Insert (set(), add()) O(1) O(1) Hash insert (amortized)
Search (get(), has()) O(1) O(1) Key lookup using hash
Delete (delete()) O(1) O(1) Hash remove (amortized)
Iteration (for…of, .entries(), .forEach()) O(n) O(n) Must visit every element
Clear (clear()) O(n) O(n) Internally resets structure
Structure Space Complexity Why
Map O(n) Stores n key–value pairs
Set O(n) Stores n unique values
Operation WeakMap WeakSet
Insert O(1) O(1)
Search O(1) O(1)
Delete O(1) O(1)
Iteration ❌ Not allowed ❌ Not allowed
Space Complexity:

Memory can be automatically freed → depends on garbage collector → not guaranteed O(n).

Interview-Ready One-Liners

Reference Code

Comparison of Map, Set, WeakMap and WeakSet - Learn More

Source Link : https://github.com/er-arunkumarselvam/ES6--JavaScript/blob/main/assets/js/mapObject.js