0

I have the following peace of code:

const reducedValue = array.reduce((acc, curr) => {
    if (decision(curr)){
        return acc++;
    }
    return acc;
}, 0);

when console.log(samApples) is always 0, even when the decision is true several times. However when I change to acc += 1 woks fine.

Why could this happen?

rigojr
  • 351
  • 2
  • 11

2 Answers2

2

The ++ operator if used after the variable (Y++ - postfix) returns the value, and then increments it. If used before the value (++Y - prefix), it increments, and then returns it:

let x = 1, y = 1;

console.log(x++); // returns x then increments

console.log(++y); // increments y and then returns it

However, you don't need to increment the accumulator, return the new value instead:

const reducedValue = array.reduce((acc, curr) => 
  acc + (decision(curr) ? 1 : 0)
, 0);

And since you can cast a boolean to a number using the unary + operator, you can shorten it to:

const reducedValue = array.reduce((acc, curr) => 
  acc + decision(curr) // acc + +decision(curr) in typescript
, 0);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

It is because of how the ++ operator works. When you do x++ x is incremented AFTER you current operation, which in your case is return and since primitive types are passed as value instead of as reference as arguments to functions, the increment is processed after the return and not carried over to the next iteration.

On contrary += are carried out immediately and thus BEFORE any other operation. Hence why this works. If you however prefer to use the ++ syntax, use it like this: ++x, since this operation is carried out BEFORE the return (and woks exactly like += 1).


Also check out this (arguably better) description on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#description


And a little proof of concept:

const val = [1,2,3,4,5,6].reduce((acc, curr) => {
   return ++acc;
}, 0);

console.log(val)
Tokimon
  • 4,072
  • 1
  • 20
  • 26