Reputation: 3919
According to MDN set Method for Map, the only way for adding key/value pair to a map in javascript is a set method. I am wondering what the behavior of a map is when we add a key/value pair with a square bracket like below;
const testMap = new Map();
testMap.set( 1,"firstValue" );
testMap[2] = "secondValue";
console.log( testMap );
console.log( testMap[ 2 ] );
console.log( testMap[ '2' ] );
It seems that we can have both a map and object together! Can somebody explain this to me? I know that Map is a kind of object but this behavior can cause a lot of bugs. Is there any way to prevent this? By the way, if you add a key/value pair with square brackets, then you cannot use get method to retrieve it.
Upvotes: 4
Views: 3851
Reputation: 25725
This is a special situation.
Maps are a special case that contain an entries
array internally.
When you use the array notation, your setting key/value pairs outside this entries
array.
When you use the set
or get
method you are actually using the internal entries
array used by the map
code.
The example above, essentially creates a Map object that is using the internal entries
array. However, setting the second object using the array notation, means you are adding another entry/property but not in the Entries array.
Also, these values are completely different. Do note though that these two data structures don't collide. So testMap.get(2) is not the same variable as testMap[2].
Upvotes: 7
Reputation: 9800
No your example doesn't work as expected, when you use brackets, you are setting a property on the testMap
object not setting an entry. You can confirm that by iterating over your map using the forEach
method for example.
const testMap = new Map();
testMap.set(1, "firstValue");
testMap[2] = "secondValue";
testMap.forEach(x => console.log(x));
As you can see, there is no secondValue
on the console, that is, there is no mapped entry with that value. Therefore, it wasn't added to the map what so ever.
And definetly,
testMap.set(1, "firstValue");
is not equivalent totestMap[1] = "firstValue";
the only reason your are allowed to do that is because javascript permit you to add property to living objects but it is not added to the map entries.Ref.: MDN Map
Upvotes: 4