0

How can I check if a JavaScript variable is a Set or Map?

There is no equivalent to Array.isArray(), so my best guess is something like:

c.__proto__.constructor.name === 'Set'

Are there any pitfalls I should be aware of with that approach? Or a better way?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
leo
  • 8,106
  • 7
  • 48
  • 80
  • 2
    Does `instanceof` not work here? E.g., `if (thing instanceof Set) {...}` – Nick Dec 05 '20 at 16:45
  • 1
    Don't ever use `__proto__`, it's deprecated. Don't use `.constructor` to check for inheritance, use `instanceof` instead. If you really were looking for a specific constructor, don't use `.name`, but compare by reference. (None of these is specific to `Map`/`Set`, actually) – Bergi Dec 05 '20 at 16:55

2 Answers2

3

If I've understand your question you can use instanceof.

Only check if your object is an instance of the desired object.

var set = new Set();
var map = new Map();
console.log("set variable is Set object:",set instanceof Set)
console.log("map variable is Set object:",map instanceof Set)
console.log("set variable is Map object:",set instanceof Map)
console.log("map variable is Map object:",map instanceof Map)

In this example, using the syntaxis myVariable instanceof MyObject the output is true when the variable is the desired object, otherwise false.

J.F.
  • 13,927
  • 9
  • 27
  • 65
2

You can use Object.prototype.toString.call, which is a robust solution that works for different frames as well.

function isSet(obj){
  return Object.prototype.toString.call(obj) === '[object Set]';
}
function isMap(obj){
  return Object.prototype.toString.call(obj) === '[object Map]';
}
console.log(isSet(new Set));
console.log(isMap(new Map));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • …robust, until someone tries to fool you with `{[Symbol.toStringTag]: 'Map'}`. `instanceof` is a better solution in general – Bergi Dec 05 '20 at 16:51