Solve - Map.has is not a function Error in JavaScript


Borislav Hadzhiev

Wed Oct 20 20212 min read


Photo by Annie Cat

Solve - Map.has is not a function Error #

The "Map.has is not a function" error occurs when we call the has() method on a value that is not a Map object. To solve the error, convert the value to a Map before calling the has method or make sure to only call the method on Map objects.

typeerror map has is not a function

Here is an example of how the error occurs.

const map = {}; // โ›”๏ธ TypeError: map.has is not a function const result = map.has('name');

We called the Map.has method on an object and got the error back.

To solve the error, make sure to only call the has method on Map objects.

const map = new Map([ ['name', 'James'], ['age', 30], ]); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ true console.log(map.has('bar')); // ๐Ÿ‘‰๏ธ false

Alternatively, you can check if the object is a Map by using the instanceof operator.

const map = new Map([ ['name', 'James'], ['age', 30], ]); if (map instanceof Map) { const result = map.has('name'); console.log(result); // ๐Ÿ‘‰๏ธ true }

The instanceof operator allows us to check if an object was created using the Map() constructor.

const map = new Map([ ['name', 'James'], ['age', 30], ]); console.log('hello' instanceof Map); // ๐Ÿ‘‰๏ธ false console.log({} instanceof Map); // ๐Ÿ‘‰๏ธ false console.log(map instanceof Map); // ๐Ÿ‘‰๏ธ true

If you need to convert an object to a Map, you can use the Object.entries method.

const obj = { id: 1, name: 'James', }; // โœ… Convert Object to Map const map1 = new Map(Object.entries(obj)); console.log(map1); // ๐Ÿ‘‰๏ธ {'id' => 1, 'name' => 'James'} // โœ… Convert Map to Object const objAgain = Object.fromEntries(map1); console.log(objAgain); // ๐Ÿ‘‰๏ธ {id: 1, name: 'James'}

We can pass an array of arrays to the Map constructor to create a Map. Each nested array should contain 2 elements - a key and a value.

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