Incorrect answers with [] and set&get of javascript map

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?

>Solution :

You are using the Map incorrectly when you use the [] notation

var mp1 = new Map(); // ok we have a map
mp1[1] = 'apple';    // adding a new property to the map object value apple
mp1[2] = 'bat';      // adding a new property to the map object value bat - neither are Map elements

console.log(mp1.size); // Yep, the map has nothing set so the size is 0
console.log(mp1.set(1, 'test')); // NOW we use the set correctly 
console.log('using get', mp1.get(1)); // and get too
console.log('using[]', mp1[1])
console.log('------------');

var mp2 = new Map(); // yep we have a Map
mp2.set(1, 'match'); // setting 1 to contain "match"
mp2.set(2, 'testing'); // setting 2 to contain "testing"

console.log(mp2.size); // yes we have two items
console.log('using []', mp2[1]) // this is not the way to get it 
console.log('using get', mp2.get(1)) // this is better

// If you want to access the elements using [] then spread to an array first:
const arr = [...mp2]; 
console.log("Using array notation",arr[1][1])

Leave a Reply