Ufuk's Blog

How to factorialize a number in JavaScript

☕️ 1 min read

There are two possible way I know to solve this problem. First one is writing a function in an imperative way, second one is writing a function in a recursive way. Let’s take look at the imperative way first.

function factorialize(num) {
  let result = 1;

  // loop works 'til the num is 0
  for (let i = num; i > 0; i--) {
    // result multiplies as long as loop works
    result *= i;
  }

  return result;
}

factorialize(5);

Another approach to this problem in the section below. We name the functions that call themself recursive functions. They look cleaner but hide complex operations behind the scene.

function factorialize(num) {
  if (num === 0 || num === 1) return 1;
  // this function calls itself to do the job!
  return num * factorialize(num - 1);
}