Ian
Ian

Reputation: 6134

Why doesn't the Map size property update when I add a key/value pair using bracket notation?

According to MDN, the size property of a Map object should represent the number of entries the Map object has. However, if I create an empty Map and use the bracket notation (not sure what the formal name for this is) to add a key/value pair, the size property is not updated. However, if I use the Map.set(key, value) function, then the property is updated. Why is this?

Example:

var ex = new Map();
ex['key1'] = 'value1';
ex.set('key2', 'value2');

After running this, ex.size returns 1.

Upvotes: 3

Views: 855

Answers (2)

Felix Kling
Felix Kling

Reputation: 816810

Because adding a property to the map object is not the same as adding an element to the map (and vice versa). Try ex.get('key1') (and ex['key2']). Only Map#set adds an element to the map. Maybe it becomes clearer if you consider this poor and limited implementation of Map:

class Map {
  constructor() {
    this._items = {};
  }

  set(key, value) {
    this._items[key] = value;
  }

  get(key) {
    return this._items[key];
  }

  get size() {
    return Object.keys(this._items).length;
  }
}

Adding a property to an instance of the class would not affect this._items, which is where the map entries are stored.


You can add arbitrary properties to basically any object in JavaScript, but that doesn't mean that the object is doing anything with them.

The most confusing case is probably arrays. Only properties whose numeric value is between 0 and 2^32 are considered "elements" of the array. So when I do

var arr = [];
arr.foo = 42;

then arr.length will still be 0.

Upvotes: 8

Majid Laissi
Majid Laissi

Reputation: 19788

Because ex['key1'] = 'value1'; just added a new property key1 to the object ex (that happens to be of type Map).

It does not affect the content of the actual Map.

Upvotes: 2

Related Questions