Basic Algorithm Scripting: Factorialize a Number

Basic Algorithm Scripting: Factorialize a Number
0

#1

Basic Algorithm Scripting: Factorialize a Number

The challenge:
Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120

Only integers greater than or equal to zero will be supplied to the function.

Remember to use Read-Search-Ask if you get stuck. Write your own code.

My code:

var arr = [];
var newArr = [];
function factorialize(num) {
  if (num == 0) {
    var forZero = 1;
    return forZero;
    } else {
      for (var i = 1; i <= num ; i++) {
      var product = arr.push(i);
    }
    console.log(arr);
    newArr = arr.reduce(
     (counter, current) => counter * current);
  return newArr;
  }
}
factorialize(10);

My problem:
Even though my code is returning the right answers, when I run it, the test won’t accept them and give me the check marks for all each of the requirements.

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number


#2

Don’t make arr and newArr global. Move them inside your function.

Why? Because the tests run one after the other using your code and calls your function multiple times. arr and newArr will retain the values they had from the previous call going into the next call to the function. Moving them inside allows them to be reset to empty arrays every time the function is called.