Factorialize a Number - JavaScript Solution & Walkthrough

(03/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum

Factorialize a Number - JavaScript Solution & Walkthrough

03/16 Factorialize a Number

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.

function factorialize(num) {

  return num;
}

factorialize(5);

Credit: FreeCodeCamp.org

Understanding the Challenge

In this challenge, your task is to create a function which returns a factorial of a given number. The definition of a factorial has been given as "the product of all positive integers less than or equal to n" In other words, to find the factorial of a number, you've got to multiply all whole numbers from 1 to that number. The product (or result) of that multiplication is what is referred to as the factorial of that number.

Now, we have a good understanding of what the challenge expects of us. As always, let's write some pseudocode to guide us.

Pseudocode

Given a number,
  create a variable (factorial) that will hold the answer to be returned
  Loop through all numbers from 1 to the given number
  For every iteration of the loop,
    multiply the number by current value of the variable (factorial)
  Return the value of the variable (factrorial) when loop has finished running

Solving the Challenge

First, we need to create a variable. Let's call it factorial. We will set the initial value of factorial to 1. This variable will hold the final answer that the function will return.

let factorial = 1;

Next, we will use a for loop to get all the whole numbers from 1 to the given number. We'll initialize the loop at 1 let i = 1 and keep the loop running as long as i <= num.

  for (let i = 1; i <= num; i++) {
    factorial *= i;
  }

For every iteration of the loop, we're multiplying the current value of factorial by the value of i, then we increase the value of i by 1 (i++)

Finally, we return the value of factorial. And our factorialize function is complete.

return factorial;

Final Solution

function factorialize(num) {
  let factorial = 1
  for (let i = 1; i <= num; i++) {
    factorial *= i;
  }
  return factorial;
}

factorialize(5); // 120

Congratulations!

You just cracked the third challenge in this series.

Cheers and happy coding!