Why does the increment operation not work when used in return statement?

I have a very strange issue… with the ternary operator… See the below code:

let bases1 = ['C','G', 'A', 'A'] let bases2 = ['C','G', 'C', 'G'] function testReduce(bases){ numGoodBases = bases.reduce((acc, el) => { if(el === 'C' || el === 'G') acc++; return acc; },0) console.log(numGoodBases) return (numGoodBases / bases.length * 100 >= 60) } console.log(testReduce(bases1)); console.log(testReduce(bases2)); /* Returns: 2 false 4 true */ function testReduceTernary(bases){ numGoodBases = bases.reduce((acc, el) => { return el === 'C' || el === 'G' ? acc++ : acc; },0) console.log(numGoodBases) return (numGoodBases / bases.length * 100 >= 60) } console.log(testReduceTernary(bases1)); console.log(testReduceTernary(bases2)); /* Hmmm... strange, Returns: 0 false 0 false */ function testReduceTernary2(bases){ numGoodBases = bases.reduce((acc, el) => { let wtf = el === 'C' || el === 'G' ? acc++ : acc; //Lie actual... WTF??? return el === 'C' || el === 'G' ? acc++ : acc; },0) console.log(numGoodBases) return (numGoodBases / bases.length * 100 >= 60) } console.log(testReduceTernary2(bases1)); console.log(testReduceTernary2(bases2)); /* WTF? Returns: 2 false 4 true */

Anyone able to explain why testReduceTernary() does not work? And even more so, why testReduceTernary2() does, even when i dont use the wtf variable at all…

The explanation lies in the return value of acc++. In a browser console, or in an interactive node console, you can see the value returned by the operation:

> let a = 5
undefined 
> a
5
> a++
5
> a
6
>

The lines not preceded by > are what the previous line returned. a++ reassigns a to the previous value + 1, but the operation returns the original value a was assigned to. Your second attempt has an otherwise useless line of code that contains the a++ operation (let wtf = el === 'C' || el === 'G' ? acc++ : acc;), so the value you return has already been incremented. You might try using ++a instead of a++ in your testReduceTernary() function. :wink:
Check the docs for more information:

1 Like

The more you know… I wasn’t aware of the prefix increment, always used the postfix till now. Thank you very much for the explanation :+1:

1 Like