JavaScript Map has()
Syntax & Examples
Map.has() method
The has() method of the Map object in JavaScript returns a boolean indicating whether a value has been associated with the passed key in the Map object or not.
Syntax of Map.has()
The syntax of Map.has() method is:
has(key)
This has() method of Map returns a boolean indicating whether a value has been associated with the passed key in the Map object or not.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
key | required | The key of the element to test for presence in the Map. |
Return Type
Map.has() returns value of type boolean
.
✐ Examples
1 Using has() to check for a key in a Map
In JavaScript, we can use the has()
method to check if a specific key is present in a Map object.
For example,
- Create a new Map object
map
with initial key-value pairs. - Use the
has()
method to check if the key 'a' is present in themap
. - Log the result to the console using
console.log()
.
JavaScript Program
const map = new Map([['a', 1], ['b', 2]]);
const hasA = map.has('a');
console.log(hasA);
Output
true
2 Using has() to check for a non-existent key
In JavaScript, we can use the has()
method to check if a key that is not present in the Map object returns false.
For example,
- Create a new Map object
map
with initial key-value pairs. - Use the
has()
method to check if the key 'c' is present in themap
. - Log the result to the console using
console.log()
.
JavaScript Program
const map = new Map([['a', 1], ['b', 2]]);
const hasC = map.has('c');
console.log(hasC);
Output
false
3 Using has() with a Map of objects
In JavaScript, we can use the has()
method to check if an object key is present in a Map object.
For example,
- Create a new Map object
map
with initial key-value pairs where keys are objects. - Use the
has()
method to check if a specific object key is present in themap
. - Log the result to the console using
console.log()
.
JavaScript Program
const key1 = { id: 1 };
const key2 = { id: 2 };
const map = new Map([
[key1, 'value1'],
[key2, 'value2']
]);
const hasKey1 = map.has(key1);
console.log(hasKey1);
Output
true
Summary
In this JavaScript tutorial, we learned about has() method of Map: the syntax and few working examples with output and detailed explanation for each example.