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
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With