var map = {};
map[key] = value;
How can I
ES6 provides a dedicated class for maps, Map. You can easily extend it to construct a "map with a default value":
class DefaultMap extends Map {
constructor(defVal, iterable=[]) {
super(iterable);
this.defVal = defVal;
}
get(key) {
if(!this.has(key))
this.set(key, this.defVal);
return super.get(key);
}
}
m = new DefaultMap(9);
console.log(m.get('foo'));
m.set('foo', m.get('foo') + 1);
console.log(m.get('foo'))
(Ab)using Objects as Maps had several disadvantages and requires some caution.