Factorialize a Number Challenge - Solved but not Finishing?

Factorialize a Number Challenge - Solved but not Finishing?
0

#1

Tell us what’s happening:
When I test this function, it works according to the test requirements, but it is not passing it. Thoughts on why?

Thank you!

Your code so far

function factorialize(num) {
  if(num <= 1) {
    return factorial;
  }
  else {
    factorial = factorial * num;
    return factorialize(num-1);
  }
}

factorialize(5);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0.

Link to the challenge:


#2

When I tested your code, I received the following error:
ReferenceError: factorial is not defined

Indeed, because you do not initialize the ‘factorial’ variable, your script gets confused here: factorial = factorial * num;
num in your example is 5 the first time around, but factorial is undefined. Undefined * 5 throws an error.


#3

This is at the beginning of the code (before the function) but did not copy when I started the question for some reason:

“var factorial = 1;”

Thank you!


#4

In that case, you are right that you are getting the correct answers. My guess is that the tests that are being run on the back end are just being run on the function factorialize and ignoring the factorial variable outside of the function, whereas your solution requires both the function and the variable you declared outside the function. If you write a solution with nothing outside of the function, it will pass the tests (hint: write a ‘for’ loop in your function, or, for a more challenging solution, call the function recursively).


#5

If you declared

var factorial = 1;

outside the function (you declared a global variable) , then when the FCC tests are ran, factorial will keep increasing because each time the function runs you are multiplying it by other numbers. It does not get “reset” back to 1 each time a test runs the function with a new num.