Check if Object is of type Map in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Check if Object is of type Map in JavaScript #

Use the instanceof operator to check if an object is a Map - myObj instanceof Map. The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object.

index.js
const map = new Map(); map.set('name', 'Tom'); console.log(map instanceof Map); // ๐Ÿ‘‰๏ธ true console.log('test' instanceof Map); // ๐Ÿ‘‰๏ธ false console.log({} instanceof Map); // ๐Ÿ‘‰๏ธ false

We used the instanceof operator to check if the map variable has the prototype property of the Map constructor in its prototype chain.

This approach would also work if you extend the Map class.

index.js
class CustomMap extends Map { myMethod() { console.log('do work'); } } const map = new CustomMap(); map.set('name', 'Tom'); console.log(map instanceof Map); // ๐Ÿ‘‰๏ธ true console.log(map instanceof CustomMap); // ๐Ÿ‘‰๏ธ true console.log({} instanceof CustomMap); // ๐Ÿ‘‰๏ธ false

In this example, we extended the Map object and the instanceof operator returned true for both Map and CustomMap.

Using the instanceof operator is risky when working with IFrames (inline frames). The instanceof check might not work when performed in a different window context, especially on some older browsers.

As an alternative, you can use duck-typing to check if the object is a Map.

index.js
function isMap(map) { if ( map && typeof map.clear === 'function' && typeof map.delete === 'function' && typeof map.get === 'function' && typeof map.has === 'function' && typeof map.set === 'function' ) { return true; } return false; } const map = new Map(); console.log(isMap(map)); // ๐Ÿ‘‰๏ธ true const set = new Set(); console.log(isMap(set)); // ๐Ÿ‘‰๏ธ false console.log(isMap({})); // ๐Ÿ‘‰๏ธ false

A simple way to think about duck-typing is - we're basically saying:

A Map has the following properties / methods. If an object also has these properties/methods, then it must be a Map.

In our isMap function we check if the passed in parameter has the methods a Map would have, if the condition is met, we return true.

This could go wrong if an object, that is not a Map, but contains these same methods gets passed to the function.

index.js
function isMap(map) { if ( map && typeof map.clear === 'function' && typeof map.delete === 'function' && typeof map.get === 'function' && typeof map.has === 'function' && typeof map.set === 'function' ) { return true; } return false; } // ๐Ÿ‘‡๏ธ true console.log( isMap({ clear: () => {}, delete: () => {}, get: () => {}, has: () => {}, set: () => {}, }), );

The duck-typing approach is not bullet proof either. If the object passed to the isMap function contains the properties/methods we are checking for, we get back a false positive.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee