What are alternative / better ways to check if a JavaScript object is Map or Set than:
Object.getPrototypeOf(map) === Map.prototype Object.getPrototypeOf(set) === Set.prototype
Use the instanceof operator to check if an object is a Map - myObj instanceof Map . The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object.
Few basic differences are as follows: In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!) In the Map, the original order of elements is preserved.
In Map() , key can be any type [String, number, Object] but in regular object key must be a string type. Set is one dimensional unique array, however Map is 2D and has key-value pair, where key shall be unique.
ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of any type can be used as either keys or values. A Map object always remembers the actual insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or empty Map.
Use instanceof
:
var foo = new Set; foo instanceof Set; // True! foo instanceof Map; // False!
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