Most JavaScript developers are familiar with objects and probably use them every day. Maps, on the other hand, are not as common but are still very useful. While very similar to objects on the surface, they have some very important differences. Let's take a look at them.
Object keys are limited to using only strings and symbols. Maps, on the other hand, can use values of any type as their keys, including functions and objects. This can come in handy in many different scenarios, such as memoization and data association.
const people = [
{ id: 1, name: 'John', surname: 'Doe', age: 30 },
{ id: 2, name: 'Jane', surname: 'Doe', age: 28 },
];
const peopleIndex = people.reduce((index, person) => {
index[person.id] = `${person.name} ${person.surname}`;
return index;
}, {});
// peopleIndex = {
// '1': 'John Doe',
// '2': 'Jane Doe',
// }
const peopleIndexMap = new Map(
people.map(person => [person, `${person.name} ${person.surname}`])
);
// peopleIndexMap = Map {
// { id: 1, name: 'John', surname: 'Doe', age: 30 } => 'John Doe',
// { id: 2, name: 'Jane', surname: 'Doe', age: 28 } => 'Jane Doe',
// }
Object iteration is usually accomplished using Object.keys()
, Object.values()
or Object.entries()
. All of these methods are available on Maps as part of their prototype, but they are significantly more efficient. The reason for this is that these Map methods return iterators, which are lazy and only iterate over the keys or values when they are needed. Additionally, Maps expose an iterator, which can be used with for...of
loops.
const obj = { a: 1, b: 2, c: 3 };
const objEntries = Object.entries(obj);
// ['a', 1], ['b', 2], ['c', 3]
for (const [key, value] of objEntries)
console.log(`${key}: ${value}`);
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const mapEntries = [...map.entries()]; // Same as [...map]
// [['a', 1], ['b', 2], ['c', 3]]
for (const [key, value] of map)
console.log(`${key} => ${value}`);
Apart from the two main differences mentioned already, there are some other, less noticeable, ones. These include the following:
size
property that can be used to track the number of key-value pairs.in
operator or Object.prototype.hasOwnProperty()
. Map.prototype.has()
accomplishes the same thing for Maps.Map.prototype.clear()
.JavaScript, Object
Maps an object to an object array, using the provided mapping function.
JavaScript, Object
Deep maps an object's keys.
JavaScript, Object
Maps the keys of an object using the provided function, generating a new object.