What are the differences between Map vs Object in JavaScript?
Object
The object is a data structure in which data is stored as key-value pairs. In an object, the key has to be a number, string, or symbol.
The value can be anything. It can be other objects, functions, etc. An object is a non-ordered data structure, i.e. the sequence of insertion of key-value pairs is not remembered.
In an object, the key has to be a number, string, or symbol.
Object code example:
const userObj = {}; // adding properties to an object userObj.name = 'Joe Smith'; userObj[2] = 2; // deleting a property delete userObj[2]; console.log(userObj) // {name: "Joe Smith"}
ES6 Map
ES6 Map is a data structure in which data is stored as key-value pairs. A unique key usually maps to a value. Both the key and the value can be in any data type.
A map is an iterable data structure, this means that the sequence of insertion is remembered.
In an ES6 Map, both the key and the value can be in any data type.
Map code example:
const dynamicMap = new Map(); const stringKey = 'string', objKey = {}, funcKey = function() {}; // set values to the map keys dynamicMap.set(stringKey, "value stored on a string key"); dynamicMap.set(objKey, "value stored on a object key"); dynamicMap.set(funcKey(), "value stored on a function key"); console.log(dynamicMap.size); // 3 // Get values console.log(dynamicMap.get(stringKey)); // value stored on a string key console.log(dynamicMap.get(objKey)); // value stored on a object key console.log(dynamicMap.get(funcKey())); // value stored on a function key