Variable assignment within functions what really happens with , func(a){a=b}?

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.

reduce returns a new value, you need to store it somewhere to be able to use it

also, JavaScript doesn’t have pointers, that’s a lower level language thing, not in JavaScript

What challenge is this for?

Thanks! Just saw what was going on after reading your explanation. In the NaN example the output from reduce wasn’t assigned to anything so I was trying to return a value without ever actually assigning it to the variable

This was for “Use the reduce Method to Analyze Data” in the JavaScript Algorithms and Data Structures functional programming unit.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.