Could we help you? Please click the banners. We are young and desperately need the money
JavaScript's dictionaries, generally referred to as objects, are basic and limited. Entries can strictly only be keyed by strings and doing certain interactions with them (such as iterating over all entries) requires the assistance of static methods that live on the Object class, which is hardly elegant.
Introduced with the 6th edition of JavaScript in 2015, Maps are essentially super-powered objects. Map entries' keys can be anything from primitives (that's things such as booleans, numbers, and strings), objects, and even functions. Interactions conveniently live as methods on the individual Map instances, making them accessible in an easy and consistent manner.
Let's compare Maps and Objects over some basic interactions that are possible with both. This will help us get comfortable with Maps and teach us how to transition to them from Objects.
Object
const object = {};
const object = {
'1': 1,
'2': 2,
'3': 3,
};
Map
const map = new Map();
const map = new Map([
['1', 1],
['2', 2],
['3', 3],
]);
Object
object['foo'] = 'bar';
Map
map.set('foo', 'bar');
Object
object['foo']
Map
map.get('foo')
Object
'foo' in object
Map
map.has('foo')
Object
delete object['foo'];
Map
map.delete('foo');
Object
for (const [key, value] of Object.entries(object)) {
//
}
Map
for (const [key, value] of map.entries()) {
//
}
map.forEach((value, key) => {
//
});
Object
for (const key of Object.keys(object)) {
//
}
Object.keys(object)
Map
for (const key of map.keys()) {
//
}
Array.from(map.keys())