Setting initialValue of Array.prototype.reduce with a default argument

Alan Johnson alan at breakrs.com
Wed Feb 24 23:26:34 UTC 2016


That would prevent you from using an initial value that isn’t `undefined` while also coping with a reducer that might choose to return `undefined` — it would always be converted to the initial value, when you might actually want the `undefined` to propagate.

But even without that little wrinkle, given all of the warts in Javascript and its standard library that have been kept around all these years in the name of backward-compatibility, it seems super unlikely a breaking change would be adopted.



> On Feb 24, 2016, at 6:13 PM, Zacqary Adam Xeper <zacqary.xeper at datadoghq.com> wrote:
> 
> Not sure if this has been proposed, discussed, and soundly rejected before, but I wasn't able to find any mention of it in the archives.
> 
> Let's say I'm using Array.prototype.reduce with an initialValue to convert an array into an object, like this:
> 
> ```javascript
> [0,1,2,3,4].reduce((result, val) => {
>     let key = val % 2 ? "even" : "odd";
>     return {...result, [key]: val};
> }, {})
> ```
> 
> The problem with that is it takes you all the way to the end of the function to find out what the initial value of `result` is (in this case, an object). This is bad for code readability.
> 
> Now that ES2015 has introduced default arguments, it would make a lot more sense if I could say:
> 
> ```javascript
> array.reduce( (result = {}, val) => {} )
> ```
> 
> I know this presents a backwards-compatibility issue. Is that surmountable?
> 
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160224/7c4cb54d/attachment-0001.html>


More information about the es-discuss mailing list