Skip to content
Advertisement

Map default value

I’m looking for something like default value for Map.

m = new Map();
//m.setDefVal([]); -- how to write this line???
console.log(m[whatever]);

Now the result is Undefined but I want to get empty array [].

Advertisement

Answer

First of all to answer the question regarding the standard Map: Javascript Map as proposed in ECMAScript 2015 does not include a setter for default values. This, however, does not restrain you from implementing the function yourself.

If you just want to print a list, whenever m[whatever] is undefined, you can just: console.log(m.get('whatever') || []); as pointed out by Li357 in his comment.

If you want to reuse this functionality, you could also encapsulate this into a function like:

function getMapValue(map, key) {
    return map.get(key) || [];
}

// And use it like:
const m = new Map();
console.log(getMapValue(m, 'whatever'));

If this, however, does not satisfy your needs and you really want a map that has a default value you can write your own Map class for it like:

class MapWithDefault extends Map {
  get(key) {
    if (!this.has(key)) {
      this.set(key, this.default());
    }
    return super.get(key);
  }
  
  constructor(defaultFunction, entries) {
    super(entries);
    this.default = defaultFunction;
  }
}

// And use it like:
const m = new MapWithDefault(() => []);
m.get('whatever').push('you');
m.get('whatever').push('want');
console.log(m.get('whatever')); // ['you', 'want']
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement