Sometimes, we can see code using
initialValue. For example,
const array = [1, 2, 3]; array.reduce((re, v) => re + v);
According to mdn, it is valid and seems simpler. However, is it a good practice?
Cons Brought by No
In the real world,
array could be
. In this case,
const array = ; array.reduce((re, v) => re + v);
You will got error in production!
Uncaught TypeError: Reduce of empty array with no initial value
Also, imagine that if you have met this code in your work ? What the hell does this
- Join the
- Or cumulative summation
- Or other situations?
You would never know until you have read the context.
As you can see, these are the most obvious cons brought by no
- Potential Error
- Unclear semantics
Benefits Brought with
Instead, if using
initialValue. For example, in the above case, we can write like this
const array = ; array.reduce((re, v) => re + v, 0);
- We would never meet the error!
- It is obvious that
reduceis using to do the cumulative summation job.
Safer and Clearer!