JavaScript Interview Question #190

What is the difference between Map, WeakMap, Object, and Set?

Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Object is well suited to record-like data with named properties. Map is a dedicated key-value collection that supports keys of any type, iteration, and a size property. Set stores unique values rather than key-value pairs.

Detailed Explanation

Object is well suited to record-like data with named properties. Map is a dedicated key-value collection that supports keys of any type, iteration, and a size property. Set stores unique values rather than key-value pairs.

WeakMap associates values with weakly held eligible keys and is not enumerable, making it useful for metadata tied to object lifetime. Choosing among them should reflect the data model rather than using plain objects for every collection.

Code Example

const user = { id: 1 };

const record = { name: "Asif" };

const map = new Map();
map.set(user, "metadata");

const set = new Set([1, 2, 2, 3]);

const weak = new WeakMap();
weak.set(user, { cached: true });

console.log(set.size); // 3