4
51

JavaScript: How to check if key exist in JavaScript Map

Reading Time: 2 minutes

To check if key exist in JavaScript Map, we can utilise has() without complication. This method returns a boolean result to indicate if the key exist or not.

Various Key DataType Supported

  • Primitive
  • Function
  • Objects

Before we go into the details, we have a more in-dept post here on how to create and use JavaScript Map for basic understanding.

How to check if key exist

Since JavaScript Map valid the keys based on datatype and value, we need to ensure that the correct value is pass into has() method with correct datatype to validate correctly.

In the illustration below, we have add string, numeric, boolean and object datatype keys into the map. For basic type, we can use the direct value to validate. But we will need to use the reference for object datatype key to validate if exactly same object.

const ageMap = new Map();

// Set age via string type key
ageMap.set('100', 11);

// Set age via numeric type key
ageMap.set(200, 33);

// Set age via boolean type key
ageMap.set(true, 44);

// Set age via object type key
const johnAge = {name: 'john'}
ageMap.set(johnAge, 44);

// Check if key exist
console.log(ageMap.has('100'));  // true
console.log(ageMap.has(100));    // false

console.log(ageMap.has('200'));  // false
console.log(ageMap.has(200));    // true

console.log(ageMap.has(true));   // true
console.log(ageMap.has(false));  // false

console.log(ageMap.has(johnAge));         // true
console.log(ageMap.has({name: 'john'}));  // false

if (ageMap.has('100')) {
  console.log(ageMap.get('100')); // 11
} else {
  console.log("Key not found.");
}

From the above examples, we can see that for primitive type, it is straight forward to check for a key’s existence. However, for a key like {name: 'john'}, we need to check via the reference.

Conclusion

To check if a key exist in JavaScript Map, we need to use has() method. The data that will be passed in will either be the key value directly or the reference.

For other examples, can refer to MDN documentation here.

Show Comments

No Responses Yet

Leave a Reply