If you want a result from a recursive function, all code paths through the function must return something. Your code isn't returning anything in the num!=1 case. It should be returning the result of calling itself, e.g. (see the *** line):

var fact=5;
function calfact(num)
{
 if(num!=1)
  {
   fact=fact*(num-1);
   num=num-1;
   return calfact(num); // ***
  }
 else
  {
   return fact;
  }
}

Your function is using a global variable, which isn't a great idea as it means the funtion isn't self-contained; and isn't a true factorial function, because you're effectively using two inputs (fact โ€” the global  and num, the argument)

If you want a true factorial, you don't need a global variable, just work from the argument itself:

function factorial(num) {
    if (num < 0) {
        throw new Error("num must not be negative");
    }
    if (num <= 1) {
        // Both 1! and 0! are defined as 1
        return 1;
    }
    return num * factorial(num - 1);
}
console.log(factorial(5)); // 120

Or of course, more compactly:

function factorial(num) {
    if (num < 0) {
        throw new Error("num must not be negative");
    }
    return num <= 1 ? 1 : num * factorial(num - 1);
}

(More about 0!: https://en.wikipedia.org/wiki/Factorial)

Answer from T.J. Crowder on Stack Overflow
Top answer
1 of 3
3

If you want a result from a recursive function, all code paths through the function must return something. Your code isn't returning anything in the num!=1 case. It should be returning the result of calling itself, e.g. (see the *** line):

var fact=5;
function calfact(num)
{
 if(num!=1)
  {
   fact=fact*(num-1);
   num=num-1;
   return calfact(num); // ***
  }
 else
  {
   return fact;
  }
}

Your function is using a global variable, which isn't a great idea as it means the funtion isn't self-contained; and isn't a true factorial function, because you're effectively using two inputs (fact โ€” the global  and num, the argument)

If you want a true factorial, you don't need a global variable, just work from the argument itself:

function factorial(num) {
    if (num < 0) {
        throw new Error("num must not be negative");
    }
    if (num <= 1) {
        // Both 1! and 0! are defined as 1
        return 1;
    }
    return num * factorial(num - 1);
}
console.log(factorial(5)); // 120

Or of course, more compactly:

function factorial(num) {
    if (num < 0) {
        throw new Error("num must not be negative");
    }
    return num <= 1 ? 1 : num * factorial(num - 1);
}

(More about 0!: https://en.wikipedia.org/wiki/Factorial)

2 of 3
1
var fact=5;
function calfact(num){
   if(num!=1){
      fact=fact*(num-1);
      num=num-1;
      return calfact(num);//the missing thing
   }else{
      return fact;//why fact? i think it should be 1
   }
 }

By the way, your approach is maybe working, but really bad style.May do this:

function calfact(num){
  if(num!=1){
    return calfact(num-1)*num;
  }else{
    return 1;
 }
}

Or short:

calfact=num=>num==1?1:calfact(num-1)*num;
๐ŸŒ
Programiz
programiz.com โ€บ javascript โ€บ examples โ€บ factorial-recursion
JavaScript Program to Find Factorial of Number Using Recursion
To understand this example, you should have the knowledge of the following JavaScript programming topics: ... The factorial of a number is the product of all the numbers from 1 to that number. For example, factorial of 5 is equal to 1 * 2 * 3 * 4 * 5 = 120. ... The factorial of negative numbers ...
๐ŸŒ
W3Resource
w3resource.com โ€บ javascript-exercises โ€บ javascript-recursion-function-exercise-1.php
JavaScript recursion function: Calculate the factorial of a number - w3resource
February 28, 2025 - In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120 ...
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ javascript โ€บ examples โ€บ find-factorial-of-number-using-recursion
JavaScript Program to Find Factorial of Number Using Recursion | Vultr Docs
November 6, 2024 - Start with factorial(0), which should return 1 as per the definition of 0!. ... Test with factorial(5), expecting a result of 120 because 5! = 5 * 4 * 3 * 2 * 1 = 120. ... Try a higher number like 10 and validate the result.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ javascript-program-to-find-factorial-of-a-number-using-recursion
JavaScript Program to Find Factorial of a Number using Recursion - GeeksforGeeks
July 23, 2025 - ... function factorial(n) { if (n === 0 || n === 1) { return 1; } else { return n * factorial(n - 1); } } let num1 = 6; let result = factorial(num1); console.log("The factorial of given number is :" + result);
๐ŸŒ
Medium
medium.com โ€บ @roshan.waa โ€บ understanding-recursion-in-javascript-a-step-by-step-guide-with-factorial-example-and-how-it-works-aaa4ebbb4d0d
Understanding Recursion in JavaScript: A Step-by-Step Guide with Factorial Example and How it Works? | by roshan.waa | Medium
May 4, 2023 - The factorial of a number n is defined as the product of all positive integers less than or equal to n. factorial(n) = n * (n - 1) * (n - 2) * ... * 2 * 1 ยท Here is an implementation of the factorial function using recursion in JavaScript:
๐ŸŒ
Ovexro
blog.ovexro.com โ€บ home โ€บ education & e-learning โ€บ understand recursion: a simple javascript factorial example
Understand Recursion: A Simple JavaScript Factorial Example โ€“ OVEX TECH
The factorial of 5 is found by multiplying 5 by 4, then by 3, then by 2, and finally by 1. This calculation results in 120. You can see a pattern here: the multiplication continues until we reach 1. This pattern of multiplying down to 1 is important.
Published ย  5 days ago
Find elsewhere
๐ŸŒ
Dillion's Blog
dillionmegida.com โ€บ p โ€บ factorial-with-recursion-in-js
How to find the factorial of a number using Recursion in JavaScript - Dillion's Blog
October 7, 2022 - Let more about recursion with more ... and multiples it by the number before n, that is, n - 1: function factorial(n) { const preceding = n - 1 return n * preceding }...
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ calculate-factorial-with-javascript-iterative-and-recursive
Calculate Factorial With JavaScript - Iterative and Recursive
March 23, 2023 - We'll generally just need a counter ... calculating a factorial for. ... function getFactorialForLoop(n) { let result = 1; if (n > 1) { for (let i = 1; i <= n; i++) { result = result * i; } return result; } else { return "n has to be positive"; } }...
๐ŸŒ
Joel Olawanle
joelolawanle.com โ€บ blog โ€บ recursion-in-javascript-explained-for-beginners
Recursion in JavaScript: Explained for beginners | Joel Olawanle
April 10, 2023 - Try what you have learned in the interactive code editor below. const factorial = (n) => { // base case if (n == 1) { return 1; } // recursive call return n * factorial(n - 1); }; let answer = factorial(5); document.write(answer);
๐ŸŒ
JavaScript.info
javascript.info โ€บ tutorial โ€บ the javascript language โ€บ advanced working with functions โ€บ recursion and stack
Calculate factorial
n * factorial(n - 1) : 1; } alert( factorial(5) ); // 120 ยท The basis of recursion is the value 1. We can also make 0 the basis here, doesnโ€™t matter much, but gives one more recursive step: function factorial(n) { return n ?
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ recursion-in-javascript
What is Recursion in JavaScript?
April 2, 2025 - Recursion and loops work in similar ways. Every recursive function you write has an alternative solution with a loop. For example, you can create a function to find the factorial of a given number using both recursion and loops.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-factorialize-a-number-in-javascript-9263c89a4b38
Three Ways to Factorialize a Number in JavaScript
March 16, 2016 - function factorialize(num) { // If the number is less than 0, reject it. if (num < 0) return -1; // If the number is 0, its factorial is 1. else if (num == 0) return 1; // Otherwise, call the recursive procedure again else { return (num * factorialize(num - 1)); /* First Part of the recursion method You need to remember that you wonโ€™t have just one call, youโ€™ll have several nested calls Each call: num === "?" num * factorialize(num - 1) ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ i can't understand this factorial function
r/learnprogramming on Reddit: I can't understand this factorial function
January 22, 2022 -

So I was watching a JavaScript tutorial series and the current topic was Function Expressions then I searched in google "javascript when do u assign a function to a variable" the top search result was the MDN Web Docs for JS Functions. As I was reading the documentation I came across this example function:

function factorial(n) {
  if ((n === 0) || (n === 1))
    return 1;
  else
    return (n * factorial(n - 1));
}

I know what factorial is but I can't understand how the function got the answer the else part is confusing to me, this is also the first time I came across a function that calls itself.

Can somebody explain to me how the else part works? I just can't get over this simple example. Thanks!

๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ recursion in functional javascript
Recursion in Functional JavaScript โ€” SitePoint
November 11, 2024 - We want any functions that are going to call themselves to exit quickly and cleanly when they get to their terminal case. For a factorial calculated this way, the terminal case comes when the number passed in is zero or negative (we could also test for negative values and return a different message, if we so desired). One problem with contemporary implementations of JavaScript is that they donโ€™t have a standard way to prevent recursive functions from stacking up on themselves indefinitely, and eating away at memory until they exceed the capacity of the engine.
๐ŸŒ
GoLinuxCloud
golinuxcloud.com โ€บ home โ€บ javascript โ€บ javascript recursion function to find factorial [solved]
JavaScript Recursion Function to Find Factorial [SOLVED] | GoLinuxCloud
January 17, 2023 - Recursive functions can be used ... smaller number. For example, the factorial of 5 can be expressed as 5 x the factorial of 4, which in turn can be expressed as 4 x the factorial of 3, and so on....
๐ŸŒ
JavaScript.info
javascript.info โ€บ tutorial โ€บ the javascript language โ€บ advanced working with functions
Recursion and stack
In other words, the result of factorial(n) can be calculated as n multiplied by the result of factorial(n-1). And the call for n-1 can recursively descend lower, and lower, till 1. function factorial(n) { return (n != 1) ?
๐ŸŒ
Programiz
programiz.com โ€บ javascript โ€บ recursion
JavaScript Recursion (with Examples)
Note: Without base cases, a recursive function won't know when to stop, resulting in an infinite recursion (error). ... Now, let's see an example of how we can use recursion to find the factorial of a number.
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ sorting-and-searching-algorithms-in-js โ€บ lessons โ€บ exploring-the-magic-of-recursion-in-javascript
Exploring the Magic of Recursion in JavaScript
In this function, similarly, with the factorial calculation, we pass Math.floor(num / 10) to the next recursion level, effectively dropping the last digit in each recursive call. ... Let's wrap up here. We dove into the sea of recursion, familiarized ourselves with vital concepts like base ...