I was amazed by the following code in javascript
var mp1 = new Map();
mp1[1] = 'apple';
mp1[2] = 'bat';
console.log(mp1.size);
console.log(mp1.set(1, 'test'));
console.log('using get', mp1.get(1));
console.log('using[]', mp1[1])
console.log('------------');
var mp2 = new Map();
mp2.set(1, 'match');
mp2.set(2, 'testing');
console.log(mp2.size);
console.log('using []', mp2[1])
console.log('using get', mp2.get(1))
Following result obtained for the above code
0
[object Map]
using get "test"
using[] "apple"
2
undefined
"using []" undefined
"using get" "match"
In mp1 object the size is shown as 0 but in mp2 the size is showing correctly. Also for the same key [] and set&get gave different answers. Can someone provide an explanation for this?
2
Answers
The
Map
isn’t a usual JS object where you add keys to it likemap[key] = value
. You should use the Map’s methods.When you
map[key] = val
you just add property to the Map’s instance (you can do that with any instance in JS, for example you can add a property to a function). But you don’t add any key/value to the Map’s content that way.So you should use
Map::set()
only for working with the Map’s content.I guess this misleading also could happen after working with
localStorage
where you can actually use instance properties to work with the content. But again that’s not recommended overlocalStorage::setItem()
.You can easily check that you don’t add anything to the map:
You are using the Map incorrectly when you use the [] notation