0

my goal : I want to understand why reduce isn't working as I intended, not how to get the value I expected with other method

my expected results : I expect to have the acc evaluates to sum of 1 in the array but the result I have was 0. yet when I change the acc++ to console.log(item), all item pass the if condition and the value is 1, as expected.

    function testReduce() {
        let a = [1,1,1,1,1,1,1,1,1].reduce((acc, item) => item == 1 ? acc++ : acc,0)
        return a;
    }
    
    console.log(testReduce());
LucasLucas
  • 13
  • 1
  • `acc++` won't have any effect as `number` values are not passed by-reference. Postfix increment happens _after_ the rest of the expression runs. Consider using `++acc` or `acc += 1` instead. – Dai Apr 13 '22 at 06:12
  • @Dai Or just return `acc + 1` which is the least likely to confuse. – Robby Cornelissen Apr 13 '22 at 06:16
  • 1
    @RobbyCornelissen Ah yes - I've been getting into the habit of using `+= 1` instead of `++` everywhere ever since Apple removed the `++` operator from Swift (now we just need all the other footgun languages out there to do the same...) – Dai Apr 13 '22 at 06:17
  • 1
    @Dai Footgun languages :P – Robby Cornelissen Apr 13 '22 at 06:18
  • thanks! yes I did remember learning abt postfix and prefix ++. so this is where it can hurt. – LucasLucas Apr 13 '22 at 06:31

1 Answers1

3

Post-increment behavior: acc will be returned before it is incremented.

To avoid confusion, just return acc + 1:

function testReduce() {
  let a = [1, 1, 1, 1, 1, 1, 1, 1, 1]
    .reduce((acc, item) => item == 1 ? acc + 1 : acc, 0);
  return a;
}

console.log(testReduce());
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156