0

I was trying to get and set the value of a map like an object in JavaScript. I was successfully able to do that. Still I have a doubt whether this is the right way to go about it or will my code break at any point of time?

    m = new Map();
    Map {}
    > m.set('a', 1) //set value
    Map { 'a' => 1 }
    > m.get('a') //get it
    1
    > m['b'] = 2 //try using more convenient [] notation
    2
    > m['b'] //it works!
    2

Though this works fine for this particular scenario or other scenarios, is there a scenario where getting a map using m['b'] would fail?

Dipesh Desai
  • 96
  • 1
  • 10
  • 1
    It doesn't 'work'. Maps are objects, and like any object you can add properties whenever you want, but it's not the same as using `.set`. If your keys are all strings, just use a plain object instead. – Jared Smith Sep 20 '18 at 01:40
  • 1
    Possible duplicate of [Map vs Object in JavaScript](https://stackoverflow.com/questions/18541940/map-vs-object-in-javascript) – Jared Smith Sep 20 '18 at 01:43

1 Answers1

1

They're not the same. When you're using bracket notation (or dot notation) rather than .set and .get, you're using the Map as a plain object, not a Map. For example, if you try accessing b afterwards using m.get, it won't work, because b is not a key in the map, but a property of the m object:

const m = new Map();
m.set('a', 1) //set value
m['b'] = 2 //try using more convenient [] notation
m['b'] //it works!
console.log(m.get('b')) // ...or not

You can use a Map as an object like that, and get/set arbitrary properties rather than .get and .set methods, but it'll be pretty confusing. Better to use a plain object when appropriate, or to use a Map with .get and .set methods - but don't mix the two syntaxes.

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209