InterviewSolution
| 1. |
var length = 10; function fn() { console.log(this.length); } var obj = { length: 5, method: function(fn) { fn(); arguments[0](); } }; obj.method(fn, 1); |
|
Answer» Map and WeakMap are data structures that were introduced in ES6. Map is a collection of elements where each ELEMENT is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key,value pair in the same order as inserted. Let’s find out the reason for Map by analysing a problem with Objects. In the below example, we have an object “x” and another object “a”. Now we are using “a” as a key and push a value to “x”. Now, if we console log “x” the key is shown as [object object], but then also we can extract it’s value by x[a]. But the real problem occurs when we add another object to “x” for key. It over-writes the earlier object. This occurs because in JavaScript we can have only 1 key as an object. Now we will look at how Maps help. We CREATE Map by the new keyword. And also to add to Map we NEED use one of its method set. Notice that the __proto__ object contains Symbol.iterator, so the for..of loop can be used to iterate over it like arrays. The same is not true for Objects. We iterate over Map using the for..of loop. We get an array of [key, value] for each element in Map. So, we de-structure it into [key, value] pair. If we add the same object as key as in line 9 for “a”, the Map will over-write the OLD value of the key. There is one problem with Map and it is that it holds the Map’s key, even if the original key is deleted. That is the reason we use WeakMap. So, WeakMap allows garbage collector to work as it holds a weak reference to its key but Maps doesn’t allow garbage collector to work. Another difference is that keys of WeakMaps are of type Object only. Primitive data types(Number, String, Boolean, Symbol) can only be used in Maps. |
|