1

Optional initialValue?

Sometimes, we can see code using reduce without 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 initialValue

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 reduce do?

  • Join the string
  • 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 initialValue.

  • Potential Error
  • Unclear semantics

Benefits Brought with initialValue

Instead, if using reduce with 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 reduce is using to do the cumulative summation job.

Safer and Clearer!

Issue

Source

Reference


xianshenglu
4.5k 声望2.9k 粉丝

简单、高性能