<aside> 💡 Publication date: 02/08/2021

</aside>

Introduction

With Data Structures we can store, organize, order and handle data. We need to understand how and when use determinate structures.

JavaScript has some built-in structures introduced on es6 version, even though these data structures have some time of existence has many developers has doubt about how to use them, today I wanna try to clarify the information about these.

Map

Map is an object and works as a common object, the major difference between them is because map lets you work with internal functions to make the insertion, deletion or get one element with a more simplistic form.

Also, Map only permit a unique key with diferents values. So if I create a map like this:

const map = new Map();

map.set("first", 1);

console.log(map.get("first")); // 1

map.set("first", 100);

console.log(map.get("first")); // 100

console.log(map.size); // 1

We can note the value is changed but only one key as stored on our Map.

Map is iterable, so we can use a for..of or for each to iterate through our structure and make operations there.

const map = new Map();

map.set("first", 1);

map.set("second", 2);

for (let item of map) {
	console.log(item);
}

for (let [key, value] of map.entries()) {
	console.log(key, value);
}

for (let key of map.keys()) {
	console.log(key);
}

for (let value of map.values()) {
	console.log(value);
}

map.forEach((item, key) => {
	console.log(key, item);
});

With for...of each iteration return an array like this [key, value], with forEach on each we have three parameters, first the value, them the key and finally the map itself.

Why/When use Map?

We wanna use Map structure when it's necessary to keep control of information about the object, and we need to keep keys unique, also Map has a simple usage, so it's simple to get used to using.

WeakMap

WeakMap is a collection of key/value in which keys are weakly referenced.

Because keys are weakly referenced, they cannot be enumerated, so we can't iterate them like Map and cannot obtain the keys.

We can use WeakMaps like this:

const weakMap = new WeakMap();

const value1 = {};

const value2 = function () {};

const value3 = "I'm the third value";

const value4 = { foo: "foo" };

const value5 = { key: "foo" };

weakMap.set(value1, value2);

console.log(weakMap.has(value3)); // false

// Returns the value based on key, in this case function() {}
console.log(weakMap.get(value1));

weakMap.delete(value1);

weakMap.set(value5, value4);

// Using a object that already in memory, we can access the position
console.log(weakMap.get(value5));

weakMap.set({ myKey: "myKey" }, { value: 1 });

// Will return undefined, because the object on function
// call is one and the object on the set function is another
console.log(weakMap.get({ myKey: "myKey" }));

Note: We can't use primitives values like keys with WeakMaps