Check if a Key exists in a Map using JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

Photo by Iswanto Arif

Check if a Key exists in a Map in JavaScript #

To check if a key exists in a Map, call the has() method on the Map, passing it the name of the key as a parameter. The has method returns true if the specified key exists in the Map, otherwise it returns false.

index.js
const map = new Map(); map.set('name', 'Tom'); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ true console.log(map.has('age')); // ๐Ÿ‘‰๏ธ false

The only parameter the Map.has method takes is the name of the key to test for presence in the Map.

The has method returns a boolean result:

  • true if the key exists in the Map object
  • false if the key doesn't exist in the Map object

The has method returns true, even if the key is set to undefined, null or any other falsy value.

index.js
const map = new Map(); map.set('undef', undefined); map.set('null', null); map.set('nan', Number.NaN); console.log(map.has('undef')); // ๐Ÿ‘‰๏ธ true console.log(map.has('null')); // ๐Ÿ‘‰๏ธ true console.log(map.has('nan')); // ๐Ÿ‘‰๏ธ true

The method checks for existence, not whether the value is truthy or falsy.

If a value gets deleted from the map, the has method picks up the update immediately.

index.js
const map = new Map(); map.set('name', 'Tom'); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ true map.delete('name'); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ false

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee