Factorialize a Number - Global vs Local var (thank you ArielLeslie!) [SOLVED]

Hello,

Yes there;s a very similar thread to this BUT:

I’m so very very proud I managed to get it entirely by myself and so instead of changing my code to have it pass the test (240), I’d like to understand what is wrong with it.

I’ve tested it in repl/it for all the values and I have the right answers. When testing it on FCC I also get the answers but it won’t show as correct.

(PS I’ve read something really clever about not needing an array and simply multiply bla bla bla, and yes it looked a lot smarter and cleaner but like I said…I DID IT ON MY OWN!!! YESSSS!)

Thanks a lot for your help,

 var array = [];     
 var singleVal;
function factorialize(num){

    if(num === 0){
      return 1;
    }
    else{
      for(num; num > 0; num --){
        array.push(num);
      }
    singleVal = array.reduce(function(accumulator, currVal)
        {return accumulator * currVal;
          
        });
    } return singleVal;

}

factorialize(10);

You are using global variables.

Global variables persist after function calls have completed, so we have to be very careful about modifying globals in functions. Your code relies on array being an empty array when the function is called, but after factorialize has been executed it is no longer an empty array. This means that your function will only work once.

I think I understand the logic in what you say, yet I’m puzzled…

I don’t set my array anywhere in the conditions of my function,
so why should my function consider it important for my array to remain empty?

Maybe there is no proper answer to this.

And thank you, I would have never inferred what you said from re-reading about global vs local variables.

Also then I don’t understand why the console displays the right answers anyway instead of error or something.

You are pushing to it, so the array keeps getting longer every time the function is run. After running factorialize(10); the value of array is [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]. That means when factorialize is run again it will keep pushing num onto that array and perform the reduce on the whole thing. That’s why you get the wrong answer after the first test.

1 Like

Got it ! I sort of update my original array
and so it’s the updated array that is passed into the function the next time it is called.

That being said repl/it says “local variable” about my var array AND the console still prints out the right answer in FCC.

But that will be for another time, I’m happy with your answer. Thank you very much !!

It will give the right answer the first time the function is executed (or if it is executed only once). Here is a repl.it draft where you can see that if I call factorialize(10) twice in a row I get two different answers.

1 Like

Oh you’re brilliant !! I never thought of trying that!

Thank you!!