JavaScript Interview Question #50
What is the difference between Map and a plain object?
Objects, Arrays & Core Data Handling Junior Beginner
Quick Interview Answer
Both can represent key-value data, but Map accepts keys of any type, preserves insertion order for iteration, has a size property, and provides purpose-built methods such as get, set, has, and delete.
Detailed Explanation
Both can represent key-value data, but Map accepts keys of any type, preserves insertion order for iteration, has a size property, and provides purpose-built methods such as get, set, has, and delete.
Plain objects are especially appropriate for records with known string or symbol property names and integrate naturally with JSON. Map is often a better choice for frequently changing dictionaries, arbitrary key types, or code that requires direct collection semantics.
Code Example
const objectSettings = {
theme: "dark"
};
const mapSettings = new Map();
mapSettings.set("theme", "dark");
mapSettings.set({ id: 1 }, "Object key");
console.log(objectSettings.theme);
console.log(mapSettings.get("theme"));
console.log(mapSettings.size);