Before ES6 (ECMAScript 2015), JavaScript developers relied almost entirely on standard Objects to map keys to values. While Objects are incredibly useful, they come with certain limitations (like keys being restricted to strings or symbols).
To solve these limitations, JavaScript introduced the Map data structure. A Map holds key-value pairs where the keys can be of any data type—including numbers, booleans, functions, and even other objects!
A Map is a collection of keyed data items, similar to an Object. But unlike an Object, a Map remembers the exact original insertion order of the keys.
size property.for...of loops.You can create a Map by passing an array of arrays (where each inner array contains a key-value pair) to the new Map() constructor.
// Passing an array of key-value pairs const myMap = new Map([ ["apple", 500], ["banana", 300], ["orange", 200] ]);console.log(myMap);
Alternatively, you can create an empty Map using new Map() and add elements to it later using the set() method (which we will explore in detail in the next chapter).
Because both Objects and Maps store key-value pairs, beginners often wonder: "When should I use a Map instead of an Object?"
Here is a detailed comparison table to help you decide:
| Feature | Map |
Standard Object |
|---|---|---|
| Key Types | Can be any type (functions, objects, primitives). | Keys must be Strings or Symbols. |
| Key Order | Preserves the exact insertion order. | Does not guarantee property order (though modern JS tries to for strings). |
| Size | Easily accessed using the map.size property. |
Must be calculated manually (e.g., Object.keys(obj).length). |
| Iteration | Directly iterable using for...of or .forEach(). |
Not directly iterable; requires for...in or extracting keys first. |
| Performance | Performs better in scenarios involving frequent additions and removals of key-value pairs. | Not optimized for frequent additions and removals. |
| Default Keys | Does not contain any default keys. | Contains default prototype keys (which can accidentally clash with your data). |
The most powerful feature of a Map is the ability to use complex objects as keys. This is impossible with a standard Object.
// 1. Create standard object variables
const john = { name: "John" };
const jane = { name: "Jane" };
// 2. Create a new empty Map
const userVisits = new Map();
// 3. Use the objects themselves as the keys!
userVisits.set(john, 120);
userVisits.set(jane, 55);
console.log(userVisits.get(john)); // Outputs: 120
If you tried to do this with a standard object (e.g., myObj[john] = 120;), JavaScript would convert the object john into the string "[object Object]", making it impossible to differentiate between john and jane!
Car or User).What is a primary advantage of using a JavaScript Map over a standard Object?