# What's wrong with this code?

Hi! I’ve been working on a solution to the “Sum of the first nth term of Series” CodeWars challenge, and here is my code:

``````let dividerArray = [1];
let dividerArrayElement = 1;
let numeratorArray = [1];
let combinedArray = [];
let combinedArrayElement = [];
function SeriesSum(i) {
if (i === 1) {
return "1.00";
} else {
do {
dividerArrayElement = dividerArrayElement + 3;
dividerArray.push(dividerArrayElement);
} while (dividerArray.length < i);
do {
numeratorArray.push(1);
} while (numeratorArray.length < i);

const combinedArray = numeratorArray.map((x, y) => x / dividerArray[y]);

return String(combinedArray.reduce((a, b) => a + b).toFixed(2));
}
}

console.log(SeriesSum(1), "1.00");
console.log(SeriesSum(2), "1.25");
console.log(SeriesSum(3), "1.39");
console.log(SeriesSum(4), "1.49");
``````

it passes all the “basic” test as listed above, but when it comes to additional testing on the site, it returns “test expected ‘1.57’ to equal ‘1.25’”

what could be the problem?

I know I can google solutions, but I really want to know can be improved in this particular solution.

hello, kinda need link to that challenge in order to see how the actual task look like.

Update. This one?

I am not sure why are you using so much arrays or any arrays here.

You can store/accumulate the result in a variable.
The solution can be done with a single loop.

@admit8490 yes, that one. You are correct. I know that it can be done in a more effective way.

But what’s wrong with the initial one, why doesn’t it pass the tests?

I think the above means that is doen’t pass the basic test.

1.25 - it is expectd answer for this:

so, I think your code pass the tests only for n === 1 actually.

Tbh I can’t figure out what is the actual bug in your code.

So, your code gives this output:(just checked it)

``````console.log(SeriesSum(1), "1.00");//1.00
console.log(SeriesSum(2), "1.25");//1.25
console.log(SeriesSum(3), "1.39");//1.39
console.log(SeriesSum(4), "1.49");//1.49
``````

And yet, you have this from test suite:
“test expected ‘1.57’ to equal ‘1.25’”

This is kinda controversial info, and i am a bit confused actually

interesting…

now it says

expected ‘1.63’ to equal ‘1.25’

so, don’t use global variables

@ilenia could you please elaborate on that?

See how you have all those variables over your function? There outside the function, there global variables. If you put them inside your function it will fix some of your errors.

figure out why if you call twice the function with the same input you get wrong results.

it’s all good practice, so I am not going to tell you how.

This also gives the wrong result

Note that sometimes it’s useful to have global variables - if multiple big inputs are expected, it can help with resource use.
But most often it’s just not good practice.

1 Like

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