Factorial

A factorial is the product of the integers 1 through n.

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

It is useful to calculate the amount of different combinations of a set. Specially useful when doing permutations and combinations.

Iterative factorial

  1. var factorial = function(n) {
  2. var result = 1;
  3. for(var i = 1; i <= n; i++) {
  4. result *= i;
  5. }
  6. return result;
  7. };

Recursive factorial

We don’t need to run a loop.

  1. var factorial = function(n) {
  2. // base case:
  3. if (n === 0) {
  4. return 1;
  5. }
  6. // recursive case:
  7. if (n > 1) {
  8. return n * factorial(n - 1);
  9. }
  10. return 1;
  11. };