Check If A JavaScript Object Is Of Type Set

In this article, we will cover how to check if a JavaScript object is of type Set. To achieve this, we will use the `instanceof` operator. We will check if the `prototype` property of the object `constructor` matches the `prototype` of `Set` object.

Check If A JavaScript Object Is Of Type Set

First, let’s create our `Set` object and initialize it with some values –

const set = new Set(["element1", "element2"]);

Now, let’s check if our `set` object is of type `Set` using the `instanceof` operator and print the result on the console. The `instanceof` operator should return `true` if our object matches the type `Set` and returns `false` otherwise.

console.log(set instanceof Set);
true if object matches the type set

That’s it for checking for the type `Set`. We can just wrap the logic into a function so that we can dynamically check for the type of any object we need –

const isTypeSet = (object) => {

return object instanceof Set;

};

Let’s call the `isTypeSet` function and pass in our `set` object as an argument, and then check the output on the console.

console.log(isTypeSet(set));
true is returned as set matches the type Set

As we can see, we got `true` as our `set` object matches the type `Set`.

Leave a Reply