-1

Why does the second assignment need return and the first returns variable total automatically?

const total = inventors.reduce(((total, inventor) => total += inventor.passed - inventor.born), 0);
const transportation = data.reduce(((prevVal, currentVal) => {
      if (!prevVal[currentVal]) {
        prevVal[currentVal] = 0;
      }
      prevVal[currentVal]++;
      return prevVal;
    }), {})

If return prevVal is omitted I get Uncaught TypeError: Cannot read properties of undefined

What is the difference in how reduce() acts with values. Is it effected by ternary operation? If so then why this returns 0?

const transportation = data.reduce(((prevVal, currentVal) => 
(!prevVal[currentVal]) ? prevVal[currentVal] = 0 : prevVal[currentVal]++), {})
greenbow
  • 1
  • 2
  • 1
    This is how [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#basic_syntax) work. – gen_Eric Jan 04 '22 at 17:55
  • 1
    That is just how the syntax works. If you leave out the `{}` in an arrow function's right side, the right side is expected to be an expression and automatically returned. – connexo Jan 04 '22 at 17:56

1 Answers1

0

When using curly braces with an arrow function, the return is not implicit, so you have to use return

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445