Borislav Hadzhiev
Tue Oct 19 2021·1 min read
Photo by Iswanto Arif
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
.
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
objectfalse
if the key doesn't exist in the Map
objectThe has
method returns true
, even if the key is set to undefined
, null
or any other falsy value.
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.
const map = new Map(); map.set('name', 'Tom'); console.log(map.has('name')); // 👉️ true map.delete('name'); console.log(map.has('name')); // 👉️ false