DEV Community

Discussion on: Master the Javascript Array Reduce Method with 10 Examples

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Omitting the initial value is an antipattern that makes your code much harder to reason about. Let's say you want to concatenate digits into a string (deliberately oversimplified example, you'd just use join for this in real life):

const zeroDigits = []
const oneDigit   = [1]
const twoDigits  = [1, 2]

zeroDigits.reduce((a, c) => String(a) + String(c)) // throws TypeError
oneDigit  .reduce((a, c) => String(a) + String(c)) // number 1
twoDigits .reduce((a, c) => String(a) + String(c)) // string '12'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Being 'hard to reason about' is purely subjective, and down to the individual. It's a perfectly valid language feature that has a valid use.

Thread Thread
 
lionelrowe profile image
lionel-rowe • Edited

You can't possibly be arguing that saving the 2 or 3 minified bytes from writing ,0 or ,'' or the amount of processing power required to add zero to something is somehow worth the likelihood of your code taking a single input type and outputting two unrelated types or throwing an error?

I notice your reverseStr function from your other comment suffers from this problem — did you realize that when you wrote it?

const reverseStr = str => [...str].reduce((a, v) => v + a)

reverseStr('') // throws TypeError
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

Yes