Default value argument for Map/WeakMap.prototype.get()

Tab Atkins Jr. jackalmage at gmail.com
Wed Nov 28 13:11:23 PST 2012


On Wed, Nov 28, 2012 at 12:12 PM, Andrea Giammarchi
<andrea.giammarchi at gmail.com> wrote:
> apologies, I meant it is trivial, but it depends what you are looking for /
> need
>
> So, since is that easy to create your own case, then no reason to add the
> default argument in the API

No, that's not the case.  Even if it's "trivial" to write it on your
own, if its use-case is sufficiently common, adding it helps with the
overall usability of the language.  After all, by your argument, we
don't need Map#has either, since you can get around it by just doing:

function mapset(map, key, val) { map.set(key, [val]); }
function mapget(map, key) { return map.get(key)[0]; }
function maphas(map, key) { return map.get(key) === undefined; }

This lets you store undefined in a map, and still distinguish it from
the key not being set at all, while using solely Map#get and Map#set,
and a trivial bit of code.

In this case, I agree that getting a default value from a map when the
key is undefined is extremely common (I do it regularly when using
dictionaries in Python), and it should be part of the default API.

~TJ


More information about the es-discuss mailing list