This post will discuss how to check if a value exists in a map in JavaScript. In other words, determine whether there is a key in the map that has the given value as its corresponding value.

The Map class provides the has() function that checks if the specified key exists in the map or not. However, if we need to check if a value exists in a map in JavaScript, we can use any of the following functions:

1. Using Array.includes() function

If the map is a Map object that stores key-value pairs, we can use the Map.values() function with the spread operator (…) to get an array of the map’s values, and then use the Array.includes() function to determine whether the array includes a certain value among its entries, returning true or false as appropriate. The following code illustrates this:

Download  Run Code

 
If the map is an object literal that stores key-value pairs, we can use the Object.values() function to get an array of the object’s values, and then invoke the Array.includes() function to check if the value is contained in the array. For example:

Download  Run Code

2. Using Set.has() function

Another option is to use the Set object to store the map’s values as a collection of unique values, and then use the Set.has() function to check if the value is present in the set. For example:

Download  Run Code

3. Using a cutom function

We can also create a cutom function to check if the value we are looking for is included in the values of the map. This function iterates over the key-value pairs in the map with a for…of loop and compares each value with the value we are looking for. If a match is found, it returns true. If no match is found, it returns false after completing the loop. The following code illustrates this:

Download  Run Code

That’s all about checking if a value exists in a map in JavaScript.