Using "in" keyword with maps in JS

Viewed 53
let hMap = new Map();
    
    for(let i = 0; i < nums.length; i++){
        let diff = target - nums[i];
        
        if(diff in hMap)
           return [hMap[diff], i];
        hMap[nums[i]] = i;
    }

How does if(diff in hMap) work? I tried replacing it with hMap.has(diff) but that didn't work.

2 Answers

Maps are special kinds of objects, and objects can have arbitrary key-value pairs associated with them. Here, the hMap being used is being used only for its functionality as a plain object - an association of (object property) keys to values. It is not being used as a Map, so the code is understandably confusing.

The code would work just as well (and would make a lot more sense) if it was:

let hMap = {};

At this point, it should be pretty easy to understand what's going on: hMap[nums[i]] = i; sets a property on the object, and diff in hMap checks if the property exists on the object.

If one wanted to use Maps for this exercise, it would be appropriate only if one was using the Map methods to get and set values, which are completely different from that of normal objects:

if (hMap.has(diff)) {
  return [hMap.get(diff), i];
}
hMap.set(nums[i]), i;

You cannot use in to check if a Map has a property (set by Map.set) - you can only use Map.has for that.

Similarly, you cannot use has to check if a Map or other expression (or anything else) has a property set by expression[prop] = someValue - to look up such a prop, you have to use in.

There is an error in seting and getting a map entry.

To add value with a key you need to call method

Map.set(key, value);

To get value from Map by key you need to call method

var value = Map.get(key);

You code snippet can be like that:

let hMap = new Map();
    
for(let i = 0; i < nums.length; i++){
    let diff = target - nums[i];
        
    if(hMap.has(diff)) return [hMap.get(diff), i];

    hMap.set(nums[i]) = i;
}
Related