# Map#get needs a default value param?

Tab Atkins Jr. jackalmage at gmail.com
Tue Jun 12 10:09:32 PDT 2012

```On Tue, Jun 12, 2012 at 9:07 AM, David Bruant <bruant.d at gmail.com> wrote:
> Le 12/06/2012 18:02, Tab Atkins Jr. a écrit :
>> On Tue, Jun 12, 2012 at 7:36 AM, David Bruant<bruant.d at gmail.com>  wrote:
>>> Le 12/06/2012 16:19, Hemanth H.M a écrit :
>>>
>>> Would it be useful to have something like sum[value] = sum.get(value, 0)
>>> + 1
>>>
>>> You can always do
>>>
>>>     sum[value] = (sum.get(value) || 0) + 1;
>>>
>>> I think it's simple enough to justify not having an additional (and
>>> potentially confusing) argument, but I'm open to debate.
>>
>> The default argument in python's Dict.get doesn't seem confusing, and
>> I've used it plenty.  (I've also used the more specialized Dict
>> variants that obviate it - Counter and DefaultDict.)
>
> "sum.get(value) || 0" leaves no ambiguity (assuming you know JavaScript and
> falsy values) as to when the value is 0, while for "sum.get(value, 0)", the
> implicit part is in the semantics of the function for which you need to look
> at the spec, that's what I find more confusing. YMMV.

The problem is that the simple expression works for this example,
because we know that if the value is set, it will be set to a non-zero
number.  Thus, all set values are truthy, and we can rely on undefined
being the only falsey value in the map.

In the more general case where the map might legitimately be holding
0, false, or null, this assumption breaks and you have to go with the
wordier variant:

var temp = sum.get(value);
sum.set(value, temp === undefined ? 1 : temp + 1);

Of course, the default operator would return us to your simpler expression:

sum.set(value, (sum.get(value) ?? 0) + 1;

This isn't too bad, and we can always wait for the language to expand
with subtypes of Map that handle this behavior better (or use a
library), like the aforementioned Counter and DefaultDict of Python.

~TJ
```