SHARE
TWEET

Untitled

a guest Aug 22nd, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. - [reduce initial value](#reduce-initial-value)
  2.  
  3.  
  4. <section class="qa">
  5. <details>
  6. <summary class="q">
  7.  
  8. ## reduce initial value
  9.  
  10. QUESTION: What is the problem with both snippets below?
  11.  
  12. ```js
  13. [].reduce((previous, current) => {
  14.   return previous + current;
  15. });
  16.  
  17. ''.split('').reduce((previous, current) => {
  18.   return `${previous}-${current}`;
  19. });
  20. ```
  21. </summary>
  22.  
  23. <div class="a">
  24.  
  25. ANSWER: Correct:
  26.  
  27. 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.
  28.  
  29. 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.
  30.  
  31. ```js
  32. [].reduce((previous, current) => {
  33.   return previous + current;
  34. }, 0);
  35.  
  36. ''.split('').reduce((previous, current) => {
  37.   return `${previous}-${current}`;
  38. }, '');
  39. ```
  40. </div>
  41. </details>
  42. </section>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top