JavaScript
Map vs Object
Learn the differences between Map and Object and when to use each.
Map vs Object
An Object only allows string or symbol keys; a Map accepts keys of any type. An Object's size comes from Object.keys(obj).length, while a Map exposes it directly as map.size.
Map stores keys in insertion order; Object mostly does too, but integer-like string keys may sort differently. For frequent add/remove of key-value pairs, Map is usually faster.
When should you use Object?
Still, an Object is often the right choice. If you have a fixed shape (a user object: name, email, age), an Object is more natural and shorter. Standard tools for saving objects as text or sending them over the network work directly with objects.
A Map must first be converted to an object before it can be serialized to text. When the shape rarely changes and keys are strings, an Object is usually simpler.
Exercise Use a Map for preferences
Create a Map called prefs. Add "dark" under key "theme" and "en" under key "lang". Log the result of prefs.has("theme") with console.log. Then delete the "lang" entry with prefs.delete("lang").
Show example solution
const prefs = new Map();
prefs.set("theme", "dark");
prefs.set("lang", "en");
console.log(prefs.has("theme"));
prefs.delete("lang");
Test yourself
-
When should you prefer Map over Object?
- When you need a fixed shape with known properties
- When you want to store data as text
- When only string keys are enough in simple cases
- When keys are added and removed often with mixed types
Show answer
When keys are added and removed often with mixed types — Correct. Map fits often-changing keys of mixed types.
-
Read the Map's size
const m = new Map();
m.set("a", 1);
m.set("b", 2);
console.log(m.____);
Show answer
const m = new Map();
m.set("a", 1);
m.set("b", 2);
console.log(m.size);
-
Which statement about Map is wrong?
- Keys can be objects and functions too
- Use the length property to get the size
- It preserves insertion order
- for...of yields [key, value] pairs
Show answer
Use the length property to get the size — Correct. There is no length on a Map; use size instead.
-
Match Map and Object traits
- Map.size
- Direct size
- Object.keys(obj).length
- Counts size manually
- Map key
- Any type allowed
- Object key
- String or symbol
Next lesson: Summary - Map and Set