When is a `Map` more useful than a plain JavaScript object?
Quick answer
Use a Map when your lookup is built dynamically, its keys may be values other than strings, or you want convenient entry counting and insertion-order iteration. Use a plain object when you are representing a known set of named fields, such as a configuration record. A Map supports any value as a key, exposes .size, and works directly with for...of; object keys are strings or symbols, and objects are not directly iterable that way by default. [S1][S2]
The question, the details, the next step.
A practical checklist
List whether your keys are known named fields or are created at runtime.
Check whether any key needs to be an object or another non-string value.
Choose an object for a fixed, clearly named record; consider
Mapfor a changing lookup.If choosing
Map, use.set()to add entries,.get()to retrieve them, and.sizeto count them.When iterating a
Map, usefor...ofto receive each[key, value]pair in insertion order.For object keys in a
Map, retain the original reference for later retrieval.
A few more useful answers
Does a `Map` treat two objects with identical properties as the same key?
No. Object keys are matched by identity, so you need the same object reference used when storing the entry. [S2]
Can I use `for...of` directly on a plain object?
Is `Map` always faster than an object?
The cited documentation does not establish a universal performance winner. Choose based on your keys, data shape, and need for entry counting or direct iteration. [S2]
Sources
References used for this guide.
- [S1] Keyed collections — JavaScript | MDN developer.mozilla.org · Checked
- [S2] Map — JavaScript | MDN developer.mozilla.org · Checked
