Skip to content

Instantly share code, notes, and snippets.

@FernandoBasso
Last active August 10, 2019 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FernandoBasso/754986d4883d2cd6eaddc0883de35550 to your computer and use it in GitHub Desktop.
Save FernandoBasso/754986d4883d2cd6eaddc0883de35550 to your computer and use it in GitHub Desktop.
Markdown Collapse Using Summary and Details Tags

reduce initial value

QUESTION: What is the problem with both snippets below?

[].reduce((previous, current) => {
  return previous + current;
});

''.split('').reduce((previous, current) => {
  return `${previous}-${current}`;
});

ANSWER: Correct:

The problem is that with empty arrays and no default initial values for reduce, the JS engine doesn't have anything to return and throws an exception.

TIP: Always provide an initial, default value for your reduces. 0 or 1 for reduces that sum or subtract, 1 for addition and subtraction, empty string for strings. For other cases, consider each one carefully.

[].reduce((previous, current) => {
  return previous + current;
}, 0);

''.split('').reduce((previous, current) => {
  return `${previous}-${current}`;
}, '');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment