DEV Community

Discussion on: The Most POWERFUL [JavaScript] Function

Collapse
 
val_baca profile image
Valentin Baca • Edited

You can just do:

['truck', 'car', 'people'].reduce((text, word) => `${text}-${word}`)

> "truck-car-people"
Enter fullscreen mode Exit fullscreen mode

If no initial variable is given (your first example had '') then it just pulls from the input, in this case, 'truck'

You (obviously) need an initial value if the array is empty or you get a very descriptive error:

[3, 2.1, 5, 8].reduce((total, number) => total + number, 0)
> 18.1

[3, 2.1, 5, 8].reduce((total, number) => total + number)
> 18.1

[].reduce((total, number) => total + number, 0)
> 0

[].reduce((total, number) => total + number)
> VM158:1 Uncaught TypeError: Reduce of empty array with no initial value

Enter fullscreen mode Exit fullscreen mode