0

let m = new Map();

let obj = {};

let keyString = 'a string';
let keyObj = {};
let keyFunc = function() {};

obj[keyObj] = 'object inside object as keys!';
obj[keyFunc] = function() {}


m.set(keyObj, 'object');
m.set(keyFunc, 'function');


console.log(typeof obj[keyObj]); // type = string
console.log(typeof obj[keyFunc]); // type = function 
console.log(typeof m.get(keyObj)); // type = string 
console.log(typeof m.get(keyFunc)); // type = string 
console.log(m.get(keyObj)) //  object
console.log(m.get(keyFunc)) //  function

Then what is difference between map and object? map also converts the keys type to string.

VLAZ
  • 18,437
  • 8
  • 35
  • 54
  • 4
    "*map also converts the keys type to string.*" it DOESN'T! It explicitly keeps their types by design. – VLAZ Jun 09 '20 at 12:20
  • `typeof m.get(keyObj)` returns the value for the key. It is same as `typeof "object"`. – adiga Jun 09 '20 at 12:21
  • [Showcasing preserved key types](https://jsbin.com/jebojusuwa/1/edit?js,console) – VLAZ Jun 09 '20 at 12:26

1 Answers1

0

Map is a data structure which helps in storing the data in the form of pairs. The pair consists of a unique key and a value mapped to the key. It helps prevent duplicity.

Object follows the same concept as that of map i.e. using key-value pair for storing data. But there are slight differences which makes map a better performer in certain situations.

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. This is not true in case of objects.
  • The Map is an instance of an object but the vice-versa is not true.
Yash.S.Narang
  • 378
  • 2
  • 9
  • "*In Object, the data-type of the key-field is restricted to integer, strings, and symbols.*" - it's only strings and symbols. You cannot have a number as a key, it gets converted. In few situations "numeric" keys are treated differently but those are still *strings* that contain a non-negative integer. – VLAZ Jun 09 '20 at 12:28