Search code examples
javascriptcomparison

Best way to know if something is a Map type


I think this might be a little tricky, or it might have been answered already, but I can't find it.

Anyways, I want to know if the variable that was passed in to my function is a Map()

OFC, the typeof operator would return object for a map.

I was wondering if I should be doing something like the following, would it make sense?

var something = new Map()

console.log(something.constructor.prototype.toString())
console.log(Map.prototype.toString())
console.log(something.constructor.prototype.toString() === Map.prototype.toString())

console.log(something.constructor.toString())
console.log(Map.toString())
console.log(something.constructor.toString() === Map.toString())

This means that there are 2 "hacky" ways to know which is the type, but I know this is not correct.

Can anyone come up with a better solution than comparing prototypes?


Solution

  • After a little time I just reminded the instanceof operator

    The correct way would be to use that operator, as you know for sure that it won't lead to any error when comparing it when the variable doesn't have a constructor. Like when the variable is undefined or null

    This would be correct

    var something = new Map()
    var nothing = null
    
    console.log(something instanceof Map)
    console.log(something instanceof Object)
    console.log(nothing instanceof Map)

    As pointed out int he comments, because of the way the instaceof operator works, it might be that if there is a variable that inherits from Map the instanceof validation would still be passing

    As you can see, something instanceof Object is true, which happens because the Map inherits from Object

    You can see more information about this behaviour in this SO answer and you could use the following comparator

    something.construtor === Map

    But it would have the same caveats that we were trying to avoid by using the instanceof operator