Hi all! Going through the intro javascript and I’m hitting a point of confusion.
I’m doing the exercise on the .reduce method and noticed I get an error I’ve gotten a few times before. I’ll write new code to not spoil the exercise for others.
function myFunc(inputVar) {
let outputVar = inputVar;
outputVar.reduce((counterParam, {Key1: val1}) => {
if (val1 % 2 === 0) {
counterParam.totalcount += val1;
counterParam.iters ++;
}
return counterParam;
}, {totalcount: 0, iters: 0});
return outputVar.totalcount/outputVar.iters;
}
This solution returns NaN. But if I use
let outputVar = inputVar.reduce()
Then I get the correct answer.
I’ve noticed a few times that I’m having this issue. Is there something happening here? It seems like javascript is handling outputVar like a pointer and just directly linking it to the value at inputVar, so that outputVar never gets assigned the properties of totalcount or iters.
So 1, is that what’s happening. 2, if that is what’s happening then are there good examples of how to use that to solve problems faster? I’ve seen that there are some leetcode things that can be solved faster using pointers but it’s beyond my depth at this point.