Borislav Hadzhiev
Last updated: Oct 20, 2021
Check out my new book
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.
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.