In this article we will learn how to check if object of type set in JavaScript.
It is very common to check if object of type set in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to check if object of type set.
Imagine we have set like this:
const set = new Set([1, 2, 3, 4]);
And we want to check if this object is typeof set or not.
How to solve this problem?
Use the instanceof operator to check if an object is a Set
, e.g. myObj instanceof Set
.
Solution:
The instanceof
operator returns true
if the prototype property of a constructor appears in the prototype chain otherwise returns false
.
Let's see an example
// Set
const set = new Set([1, 2, 3, 4]);
// Tests:
console.log(set instanceof Set);
console.log('set' instanceof Set);
console.log(new Map() instanceof Set);
console.log({} instanceof Set);
Output
true
false
false
false
This approach would also work if you extend the Set
class.
class CustomSet extends Set {
example() {
console.log('Do something');
}
}
const set = new CustomSet();
// Tests:
console.log(set instanceof Set); // true
console.log(new Set([1, 2, 3]) instanceof Set); // true
console.log(new Map() instanceof Set); // false
console.log({} instanceof Set); // false
Output
true
true
false
false
Thank you for reading
Thank you for reading my blog. 🚀