skip to Main Content

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


  1. The Map isn’t a usual JS object where you add keys to it like map[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 over localStorage::setItem().

    You can easily check that you don’t add anything to the map:

    const map = new Map;
    map.test = true;
    
    console.log([...map.entries()]);
    Login or Signup to reply.
  2. 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])
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search