# Factorial Practice

Hi there, I was busy with this practice section and got an error.

Everything checks out and yet, there is an errors

So the function in theory is fine, however there is a very specific issue that arises when you run it multiple times in a row, as the Codecademy checker will be doing.

let result = 1; const factorial = num => { for (let i = 1; i <= num; i++) { result *= i; } return result; } console.log(factorial(1)); console.log(factorial(2)); console.log(factorial(3));

Do you see the issue? `factorial(1)` and `factorial(2)` run fine, but `factorial(3)` gives 12 instead of 6, why is that?

Well, the value you are actually assigning the factorial to is `result`, a global variable. Therefore when the function is called multiple times in the same instance, this value persists. So after `factorial(2)`, the starting value of `result` is now `2`. This means that the code is effectively doing 212*3 which is resulting in 12. This is the issue with using global variables with functions, and why functional programming aims to prevent this sort of thing.

The best way to solve this would be to just move the declaration of result inside of the function, to make it present in the local scope rather than the global scope. This will redeclare the `result` value every single time the function is called, and prevent this issue from happening.

const factorial = num => { let result = 1; for (let i = 1; i <= num; i++) { result *= i; } return result; } console.log(factorial(1)); console.log(factorial(2)); console.log(factorial(3));

See how the values return as intended now? Whilst technically if you just called factorial(3) without any of the other ones first the code would work perfectly, it’s bad practise and also incredibly difficult to debug when you use global variables inside of functions. If a variable needs to be the same every time a function is called, it should be declared inside the function. If a variable could change in the global scope, then it should be passed in as an extra argument. You should generally never reference global variables inside of a function without passing them as an argument, as you can have issues arise exactly like this one, where the right code gives the wrong result.

1 Like