In this article we will learn how to check if map has specific element.
It is very common to check if map has specific element in JavaScript.
Problem
Sometimes you need to know if a certain element is in the map or not, and then execute certain code.
Imagine you have a map like this:
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
console.log(map);
// Map(3) { 'name' => 'John', 'age' => 30, 'isMarried' => true }
And you want to know if a specific element exists or not
How to solve this problem?
Fortunately, there is a built-in function in the map that determines whether there is a specific element in the map or not called has
.
has
method returns true or false.
Solution
As we said before, we can use has
method to solve our problem.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Checking..
console.log(map.has('name'));
console.log(map.has('age'));
console.log(map.has('country'));
Think for a second and expect the result!
Output
true
true
false
The has()
method returns a boolean indicating whether an element with the specified key exists or not. (Source: MDN)
Thank you for reading
Thank you for reading my blog. 🚀