Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- - [reduce initial value](#reduce-initial-value)
- <section class="qa">
- <details>
- <summary class="q">
- ## reduce initial value
- QUESTION: What is the problem with both snippets below?
- ```js
- [].reduce((previous, current) => {
- return previous + current;
- });
- ''.split('').reduce((previous, current) => {
- return `${previous}-${current}`;
- });
- ```
- </summary>
- <div class="a">
- 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.
- ```js
- [].reduce((previous, current) => {
- return previous + current;
- }, 0);
- ''.split('').reduce((previous, current) => {
- return `${previous}-${current}`;
- }, '');
- ```
- </div>
- </details>
- </section>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement