When should use maps? What are maps anyway?
Using an object is cool. We do it all the time -
const earth = { name: "earth", position: 3 };
What if we do not have all props at once, but rather incrementally assign props.
const earth = { name: "earth", position: 3 };
for (ele in earth) {
console.log(ele);
}
/* output
name
position
*/
The order of elements in an object is not guaranteed to be the same as provided in input.
This is where a map comes in. Although technically a map is just an instance of an object, it differs in that a map maintains the input order of its elements.
const earth = new Map();
earth.set("name", "earth");
earth.set("position", 3);
console.log(earth);
// Map { 'name' => 'earth', 'position' => 3 }
earth.forEach(ele => console.log(ele));
/* output
earth
3
*/
Although map does not appear to be drastically different, it is iterable in a different way, and the output order of elements is guaranteed to be the same as the input order.
Overall, we see the following differences b/w an object and a map.
- Execution order is maintained in a map
- Objects need to transform themselves into an array for more iteration options (e.g.
Object.keys(earth).forEach()), while a map is more direct - Subsequent to the previous point, you can also directly get the size of the map (
earth.size()) - Takes a bit more space than a simple object, but can hold more key-value pairs and also is better performant when you frequently have to add and delete keys
Do remember though - a map is also an object in Javascript.
Prefer using maps when there are frequent adds/deletes of elements, execution order is important, or when performance of a get is not high on your priority list.
Personally, I just use objects. They have grown from strength to strength as we progressed through the years, and are now directly iterable for the common use cases, are fast, and simple & consistent to use.