To check if a key exists in a map in JavaScript, you can use the has method. This method returns a boolean value indicating whether the map contains the specified key.
We can check if a key exists in a map in JavaScript using the has method, which returns true if the map contains the specified key and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.has
method to check for a specific key in the map. The has
method returns a boolean value indicating whether the map contains the specified key.console.log
.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Check if a key exists using has method
const keyExists = myMap.has('two');
// Print the result
console.log(`Does key 'two' exist? ${keyExists}`);
Does key 'two' exist? true
We can check if a key does not exist in a map in JavaScript using the has method, which returns false if the map does not contain the specified key.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.has
method to check for a specific key in the map. The has
method returns a boolean value indicating whether the map contains the specified key.console.log
.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Check if a key does not exist using has method
const keyExists = myMap.has('four');
// Print the result
console.log(`Does key 'four' exist? ${keyExists}`);
Does key 'four' exist? false
We can check if multiple keys exist in a map in JavaScript using the has method, which returns true if the map contains the specified key and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.has
method to check for multiple keys in the map. The has
method returns a boolean value indicating whether the map contains the specified key.console.log
.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Check if multiple keys exist using has method
const keyExistsOne = myMap.has('one');
const keyExistsFour = myMap.has('four');
// Print the results
console.log(`Does key 'one' exist? ${keyExistsOne}`);
console.log(`Does key 'four' exist? ${keyExistsFour}`);
Does key 'one' exist? true Does key 'four' exist? false
In this tutorial, we learned How to Check if a Key Exists in a Map in JavaScript language with well detailed examples.