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

Domenic Denicola domenic at
Wed Nov 28 11:52:50 PST 2012

Using you can do

var d = require("defined");
var x = d(m.get("key"), defaultValue);

Not sure if this is an argument for adding default value because this module is so ridiculous ... or against it since it’s so trivial to get the functionality yourself.

From: Andrea Giammarchi
Sent: ‎November‎ ‎28‎, ‎2012 ‎14‎:‎27
To: Jason Orendorff
CC: es-discuss
Subject: Re: Default value argument for Map/WeakMap.prototype.get()

it was there and it has been removed ... curious to see if it will be back.

Said that, same way you do

obj.prop = obj.prop || def;

you can do

obj.set(prop, obj.get(prop) || {});

I know it's not the equivalent since you might want to be able to set null, false, "", NaN, etc etc ... but it's easy to add utilities to current logic while it might be ambiguous to change defaultValue behavior later on.

As example, I might want to consider an inherited property as valid value while what you are suggesting, in a more generic approach, is not considering inheritance because the property is not "own"


On Wed, Nov 28, 2012 at 11:07 AM, Jason Orendorff <jason.orendorff at<mailto:jason.orendorff at>> wrote:
I propose adding an optional second argument to the .get() method on Map and WeakMap.

    Map.prototype.get(key[, defaultValue])

The default value would be returned only when the given key is not in the map. That is, in the last step of the spec for these two methods, instead of "Return undefined", it would say "Return defaultValue".

Python and Ruby have this. (In Ruby it's called "fetch".) It's handy in cases like:

    var counts = new Map;
    for (let word of words)
        counts.set(word, counts.get(word, 0) + 1);


es-discuss mailing list
es-discuss at<mailto:es-discuss at>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list