Short-Circuiting Interaction with Ternary Operator in JavaScript

53 Views Asked by At

I'm currently learning JavaScript and I encountered this problem:

const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) => 
   console.log(acc) && current % 2 === 0 
      ? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even + current} : i)
      : acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd + current} : i), 
      [{"even": 0, color: 'red'}, {"odd": 0, color: 'green'}]
);
const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) => 
   console.log(acc) || current % 2 === 0 
      ? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even + current} : i)
      : acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd + current} : i), 
      [{"even": 0, color: 'red'}, {"odd": 0, color: 'green'}]
);

When you run each of the above code, you'll notice that the first one only modifies the "odd" property which is not what I'm expecting when I used the && operator but when I changed it to the || operator I got the code that I was expecting originally. Can someone explain to me how I got those 2 outputs?

0

There are 0 best solutions below