Explain the difference between WeakMap from the Map?

Hi all. A bit do not understand the differences WeakMap from the Map. Read learn.javascript ( https://learn.javascript.ru/weakmap-weakset )
Why are these two examples work indention?
Map:
let map = new Map();

let john = {name: "John"};

map.the set(john, "1");

john = null;

console.log(map)

console.log(map.get(john));

console.log(map)

WeakMap:
let map = new WeakMap();

let john = {name: "John"};

map.the set(john, "1");

john = null;

console.log(map)

console.log(map.get(john));

console.log(map)
April 19th 20 at 12:31
1 answer
April 19th 20 at 12:33
Solution
Mdn describes perfectly the difference
Why WeakMap?
Experienced JavaScript developer will notice that the map API can be implemented in JavaScript with two arrays (one for keys, second for values) and four public API methods. Installation of elements in this map will simultaneously push the keys and values. As a result, the key indexes and the values are correct. Retrieving values from the map would require to iterate the keys to find a match, and then use the index of this matching to extract the corresponding value from the array of values.

Such a realization would be two main disadvantages. The first is O(n) search (where n is the number of keys in the map), as both operations require iterating the list of keys for a match. The second is the memory leak problem. Dictionaries hand-written array with keys will store references to objects-keys, not allowing them to be marked by the garbage collector. In the native WeakMap, object references-the keys are stored "poorly", which means that they will not prevent garbage collection in case if the other object references will not.

WeakMaps have a "weak" ("weak") treatment to the keys object, and hence a hurdle to the garbage collector, when we no longer have the object-key. WeakMaps can be especially useful for designs when you map keys with the key information which is valuable only if the key has not been garbage collected (Garbage collector).

Due to the fact that the links are weak, WeakMap keys are not enumerable (i.e. there is no method that returns the list of keys). Otherwise, the list would depend on the state of garbage collection, introducing indeterminism. If you want to have a list of keys, you should maintain yourself.

https://developer.mozilla.org/ru/docs/Web/JavaScri...

Find more questions by tags JavaScript