I am quite confused on how .reduce() work. Why is it that when I use accu.length for the ternary operator, it returns ‘foobar’, but when I use accu only, it returns ‘123456’. I am experimenting with .reduce, the code that I wrote is for experimenting.
I was expecting bar = 6 and accu = ‘123456’ when adding using accu.length in the ternary operator. But what happens is bar=’foobar’ and accu = ‘foobar’
Case 1(accu.length):
const arr = ['foo', '123456', 'fiver', 'foobar'];
const foo = arr.reduce((accu, cur) => {
let bar = '';
bar = accu.length >= cur.length ? accu.length : (accu = cur);
console.log(`accu: ${accu}`);
console.log(bar);
return bar;
});
Case 2(accu):
const arr = ['foo', '123456', 'fiver', 'foobar'];
const foo = arr.reduce((accu, cur) => {
let bar = '';
bar = accu.length >= cur.length ? accu: (accu = cur);
console.log(`accu: ${accu}`);
console.log(bar);
return bar;
});