Answer the question
In order to leave comments, you need to log in
Explain the difference between WeakMap and Map?
Hello. I don’t understand the difference between WeakMap and Map a little. Reading learn.javascript ( https://learn.javascript.ru/weakmap-weakset )
Why do these two examples work identically?
map:
let map = new Map();
let john = {name: "John"};
map.set(john, "1");
john = null;
console.log(map)
console.log(map.get(john));
console.log(map)
let map = new WeakMap();
let john = {name: "John"};
map.set(john, "1");
john = null;
console.log(map)
console.log(map.get(john));
console.log(map)
Answer the question
In order to leave comments, you need to log in
The difference is well described on mdn
Why WeakMap?
An experienced JavaScript developer will notice that the map API can be implemented in JavaScript using two arrays (one for keys, one for values) and four common API methods. Setting elements to this map will need to push the keys and values at the same time. As a result, the key and value indexes will be correct. Getting values with map will require iterating the keys to find a match, and then using that match's index to extract the corresponding value from the value array.
Such an implementation would have two major disadvantages. The first is an O(n) lookup (where n is the number of keys in the map), since both operations require iterating the list of keys to find a match. The second is the memory leak problem. In hand-written dictionaries, the array with keys will store references to key objects, preventing them from being marked by the garbage collector. In native WeakMap, key object references are stored "weakly", which means that they will not prevent garbage collection if there are no other references to the object.
WeakMaps have "weak" accesses to object keys, and therefore not hindering the garbage collector when we no longer have a key object. WeakMaps can be especially useful constructs when mapping keys to information about a key, which is only valuable if the key has not been garbage collected (Garbage collector).
Because references are weak, WeakMap's keys are not enumerable (that is, there is no method that returns a list of keys). Otherwise the list would depend on the garbage collection state, introducing indeterminism. If you want to have a list of keys, you must maintain it yourself.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question