Map.has()
The Map.has()
method in JavaScript is used to check whether a specified key exists in a Map
object. It returns a boolean value indicating the presence of the key.
Syntax
</>
Copy
map.has(key)
Parameters
Parameter | Description |
---|---|
key | The key to check for existence in the Map object. |
Return Value
The has()
method returns a boolean value:
true
– If the key exists in theMap
.false
– If the key is not found in theMap
.
Examples
1. Checking for an Existing Key
This example demonstrates how to check if a key exists in a Map
object.
</>
Copy
const users = new Map();
users.set('Arjun', 25);
users.set('Bhairav', 30);
console.log(users.has('Arjun'));
console.log(users.has('Charlie'));
Output
true
false
users.has('Alice')
returnstrue
because the key exists.users.has('Charlie')
returnsfalse
because the key is not present in theMap
.
2. Using has()
Before Accessing a Key
To prevent errors, you can use has()
to check if a key exists before accessing its value.
</>
Copy
const students = new Map();
students.set('Ram', 85);
students.set('Emma', 92);
if (students.has('Emma')) {
console.log(`Emma's score: ${students.get('Emma')}`);
} else {
console.log('Emma is not in the record.');
}
Output
Emma's score: 92
3. Checking for Non-String Keys
Since Map
allows any type of keys, has()
can be used to check for non-string keys like numbers and objects.
</>
Copy
const data = new Map();
const keyObj = { id: 1 };
data.set(keyObj, 'Object Key');
console.log(data.has(keyObj));
console.log(data.has({ id: 1 }));
Output
true
false
Since objects are compared by reference, data.has({ id: 1 })
returns false
because it is a different object from keyObj
.
4. Using has()
in Conditional Statements
The has()
method can be used to conditionally perform actions when a key is present in a Map
.
</>
Copy
const settings = new Map();
settings.set('theme', 'dark');
settings.set('notifications', true);
if (settings.has('theme')) {
console.log(`Current theme: ${settings.get('theme')}`);
} else {
console.log('Theme is not set.');
}
Output
Current theme: dark
Using has()
ensures that we only access existing keys.