Skip to content

Program for Factorial of a Number in Javascript Using Recursion and For Statements

Program for Factorial of a Number in Javascript Using Recursion and For Statements

Introduction

You can write a program to factorialize a number in Javascript using a recursive function or for statement.

Factorial in mathematics is the product of all positive integers less than or equal to a positive number. It is denoted by the integer and an exclamation point. for example:

0! = 1
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1

Factorial of a Number With For Statements (For Loop)

In this example, you will write the logic to multiply the given number by its number minus 1. To do this, define a function called factorial that expects num as a parameter.

function factorial(num) {
  for (let i = num - 1; i >= 1; i--) {
    num *= i;
  }
  return num;
}

factorial(6);
// 720

Breakdown

If you pass 6 as an argument to the factorial() function, the following steps happen:

  1. The variable i value is 5
  2. 6 (num) is multiplied by 5 (num - 1) and new value of the num is equal to 30.
  3. 30 is multiplied by 4, and the new value of num is equal to120.
  4. 120 is multiplied by 3, and the new value of num is equal to 360.
  5. 360 is multiplied by 2, and the new value of num is equal to 720.
  6. 720 is multiplied by 1, and the new value of num is equal to 720.
  7. Program exits the loop
  8. factorial() function returns the num which is equal to 720.

Now you need to write the logic to handle the negative numbers, and 0.

function factorial(num) {
  if (num < 0) {
    console.log("Number must be greater than or equal to 0");
  } else if (num === 0) {
    return 1;
  } else {
    for (let i = num - 1; i >= 1; i--) {
      num *= i;
    }
    return num;
  }
}

factorial(-1);
// Number must be greater than or equal to 0

factorial(0);
// 1

factorial(6);
// 720

Factorial of a Number Using Recursive Functions

Writing a recursive function to return the factorial of a number is similar to what you did with For Statements in the previous step.

You will need to have a base-case, for instance, if (num === 0). then another logic to call the function recursively until the base-case condition is met.

function factorial(num) {
  if (num < 0) {
    console.log("Number must be greater than or equal to 0");
  } else if (num === 0) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
}