To check if value exist in JavaScript Set, we can utilise has()
without complication. This method returns a boolean result to indicate if the value exist or not.
Various Key DataType Supported
- Primitive
- Function
- Objects
Before we go into the details, we have a more in-dept post here on how to create and use JavaScript Set for basic understanding.
How to check if value exist
Since JavaScript Set valid the values based on datatype and value, we got to ensure that the correct value is pass into has()
method with correct datatype.
In the illustration below, we have add string, numeric, boolean and object datatype values into the set. For basic type, we can use the direct value to validate. But we will need to use the reference for object datatype value to validate if exactly same object.
const randomSet = new Set();
// Set string type value
randomSet.add('100');
// Set numeric type value
randomSet.add(200);
// Set boolean type value
randomSet.add(true);
// Set object type value
const someName = {name: 'john'}
randomSet.add(someName);
// Check if value exist
console.log(randomSet.has('100')); // true
console.log(randomSet.has(100)); // false
console.log(randomSet.has('200')); // false
console.log(randomSet.has(200)); // true
console.log(randomSet.has(true)); // true
console.log(randomSet.has(false)); // false
console.log(randomSet.has(someName)); // true
console.log(randomSet.has({name: 'john'})); // false
if (randomSet.has('100')) {
console.log('100'); // 100
} else {
console.log("Value not found.");
}
From the above examples, we can see that for primitive type, it is straight forward to check for a key’s existence. However, for a value like {name: 'john'}
, we need to check via the reference.
Conclusion
To check if a value exist in JavaScript Set, we need to use has()
method. The data that will be passed in will either be the value directly or the reference.
For other examples, can refer to MDN documentation here.
No Responses Yet