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

avatar

Borislav Hadzhiev

Last updated: Oct 20, 2021

banner

Check out my new book

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.

index.js
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.

index.js
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.

index.js
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.

index.js
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.

index.js
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.

Use the search field on my Home Page to filter through my more than 3,000 articles.