In this article we will learn how to check if object of type map in JavaScript.
It is very common to check if object of type map in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to check if object of type map.
Imagine we have map like this:
const map = new Map([
['name', 'John'],
['age', 30]
]);
And we want to check if this object is typeof map or not.
How to solve this problem?
Use the instanceof operator to check if an object is a Map
, e.g. myObj instanceof map
.
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
// map
const map = new Map([
['name', 'John'],
['age', 30]
]);
// Tests:
console.log(map instanceof Map);
console.log('map' instanceof Map);
console.log(new Map() instanceof Map);
console.log({} instanceof Map);
Output
true
false
false
false
This approach would also work if you extend the Map
class.
class CustomMap extends Map {
example() {
console.log('Do something');
}
}
const map = new CustomMap();
// Tests:
console.log(map instanceof Map); // true
console.log(new Map([1, 2, 3]) instanceof Map); // true
console.log(new Set() instanceof Map); // false
console.log({} instanceof Map); // false
Output
true
true
false
false
Thank you for reading
Thank you for reading my blog. 🚀