In ES6, how can I test if a variable is an Array
or a Map
?
instance.constructor.name === 'Map'
is a risky habit, even if it's core type, doing this with your own class when minified will break the test.
What is the most reliable way to verify that the variable is an instance of Map
In ES6, how can I test if a variable is an Array
or a Map
?
instance.constructor.name === 'Map'
is a risky habit, even if it's core type, doing this with your own class when minified will break the test.
What is the most reliable way to verify that the variable is an instance of Map
6 Answers
Reset to default 6
const getType = obj => Object.prototype.toString.call(obj).slice(8, -1);
const isArray = obj => getType(obj) === 'Array';
const isMap = obj => getType(obj) === 'Map';
const arr = [];
console.log(isArray(arr)); // true
const map = new Map();
console.log(isMap(map)); // true
You can use instanceof
. It will return true/false if the object is a map or not
var a = new Map;
console.log(a instanceof Map);
For checking array use isArray method
var a= new Array;
console.log(Array.isArray(a))
Instead of checking the constructor's .name
(string) property, just check whether the constructor itself is === Map
:
const m = new Map();
console.log(m.constructor === Map);
You could check with Array.isArray
, because Map
is no Array
.
For checking the instance, you could take the instanceof
operator.
var array = [],
map = new Map;
console.log(Array.isArray(array)); // true
console.log(Array.isArray(map)); // false
console.log(array instanceof Map); // false
console.log(map instanceof Map); // true
You don't need to test if an Array
is a Map
in JavaScript, since an Array
is an Array
, it can never be a Map
.
In fact, they are not even the same kind of collection, an Array
is an indexed collection whereas a Map
is a keyed collection.
An Array can naver be a Map in javascript. You may however be confused with Object or map. To check if the javascript variable is Map
you can make use of instanceof
instance instanceof Map
To test is the variable is an instance of an Array, you can write Array.isArray(instance)
var instance = new Map;
console.log(instance instanceof Map); // true
console.log(instance instanceof Array); //false
Map
, they're entirely different constructs. – CertainPerformance Commented Feb 23, 2019 at 11:32