Published Mar 02 2018
Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! ✨
A Map data structure allows to associate data to a key.
ECMAScript 6 (also called ES2015) introduced the Map data structure to the JavaScript world, along with Set
Before its introduction, people generally used objects as maps, by associating some object or value to a specific key value:
const car = {}
car['color'] = 'red'
car.owner = 'Flavio'
console.log(car['color']) //red
console.log(car.color) //red
console.log(car.owner) //Flavio
console.log(car['owner']) //Flavio
ES6 introduced the Map data structure, providing us a proper tool to handle this kind of data organization.
A Map is initialized by calling:
const m = new Map()
You can add items to the map by using the set
method:
m.set('color', 'red')
m.set('age', 2)
And you can get items out of a map by using get
:
const color = m.get('color')
const age = m.get('age')
Use the delete()
method:
m.delete('color')
Use the clear()
method:
m.clear()
Use the has()
method:
const hasColor = m.has('color')
Use the size
property:
const size = m.size
You can initialize a map with a set of values:
const m = new Map([['color', 'red'], ['owner', 'Flavio'], ['age', 2]])
Just like any value (object, array, string, number) can be used as the value of the key-value entry of a map item, any value can be used as the key, even objects.
If you try to get a non-existing key using get()
out of a map, it will return undefined
.
const m = new Map()
m.set(NaN, 'test')
m.get(NaN) //test
const m = new Map()
m.set(+0, 'test')
m.get(-0) //test
Map offers the keys()
method we can use to iterate on all the keys:
for (const k of m.keys()) {
console.log(k)
}
The Map object offers the values()
method we can use to iterate on all the values:
for (const v of m.values()) {
console.log(v)
}
The Map object offers the entries()
method we can use to iterate on all the values:
for (const [k, v] of m.entries()) {
console.log(k, v)
}
which can be simplified to
for (const [k, v] of m) {
console.log(k, v)
}
const a = [...m.keys()]
const a = [...m.values()]
A WeakMap is a special kind of map.
In a map object, items are never garbage collected. A WeakMap instead lets all its items be freely garbage collected. Every key of a WeakMap is an object. When the reference to this object is lost, the value can be garbage collected.
Here are the main differences:
A WeakMap exposes those methods, which are equivalent to the Map ones:
get(k)
set(k, v)
has(k)
delete(k)
The use cases of a WeakMap are less evident than the ones of a Map, and you might never find the need for them, but essentially it can be used to build a memory-sensitive cache that is not going to interfere with garbage collection, or for careful encapsualtion and information hiding.