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
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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
🌐
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 - When the function is called with a number greater than 1, the recursive case is executed. The function multiplies the number by the factorial of the number minus 1. This process continues until the base case is reached.
🌐
Programiz
programiz.com › javascript › examples › factorial-recursion
JavaScript Program to Find Factorial of Number Using Recursion
When the user enters a positive number or 0, the function factorial(num) gets called. If the user enters the number 0, the program will return 1. If the user enters a number greater than 0, the program will recursively call itself by decreasing the number.
🌐
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 }...
🌐
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 - Learn that in the case of factorial calculation, the recursive relation is n! = n * (n-1)!, and the base case is typically 0! = 1. Define a JavaScript function named factorial that accepts one parameter n, the number whose factorial is required.
🌐
Stack Abuse
stackabuse.com › calculate-factorial-with-javascript-iterative-and-recursive
Calculate Factorial With JavaScript - Iterative and Recursive
March 23, 2023 - So it calls the function once again, but this time the if block, or rather, the base class succeeds to return 1 and breaks out from the recursion. Following the same pattern upwards, it returns each function result, multiplying the current result with the previous n and returning it for the previous function call. In other words, our program first gets to the bottom of the factorial (which is 1), then builds its way up, while multiplying on each step.
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
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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;
🌐
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 ...
Find elsewhere
🌐
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 * ...
🌐
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);
🌐
Algorithms
alg24.com › en › factorial-in-javascript-recursive
Factorial in JavaScript - recursive - What is an algorithm?
If so, in line 8 we specify the result of the function as n multiplied by the value of the factorial function (the same factorial function we are currently defining) for n minus 1 (4). At this point, the factorial function calls itself. We call this a recursive function. If n is not greater than 1, then in line 10 we set the result of the function equal to 1 (recursion termination condition) - block (5). In line 13, we declare a variable n using the var keyword, while the assignment operator ("=") initializes this variable with the value entered by the user using the prompt() statement - block (2) of the algorithm. prompt - JavaScript standard function - displays a text input pop-up on the screen.
🌐
TutorialsPoint
tutorialspoint.com › calculating-factorial-by-recursion-in-javascript
Function to compute factorial of a number in JavaScript
<!DOCTYPE html> <html> <head> ... </html> ... Recursion provides an elegant solution by calling the function itself with decremented values until reaching the base case....
🌐
GitHub
gist.github.com › 0481beeb605650c4bd402bf3f74f7eb9
Factorial recursive operator in JavaScript · GitHub
Factorial recursive operator in JavaScript. GitHub Gist: instantly share code, notes, and snippets.
🌐
LabEx
labex.io › tutorials › javascript-factorial-of-number-28293
Factorial of Number: Recursion in JavaScript | LabEx
Learn how to calculate the factorial of a number using recursion in JavaScript, including handling negative numbers with TypeError.
🌐
SitePoint
sitepoint.com › blog › javascript › recursion in functional javascript
Recursion in Functional JavaScript — SitePoint
November 11, 2024 - 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.
🌐
CoreUI
coreui.io › answers › how-to-calculate-the-factorial-of-a-number-in-javascript
How to calculate the factorial of a number in JavaScript · CoreUI
June 4, 2026 - function factorialRecursive(n) { validateFactorialInput(n) if (n <= 1) return 1 return n * factorialRecursive(n - 1) } factorialRecursive(5) // 120 factorialRecursive(10) // 3628800 · Caution: Each recursive call adds a stack frame. For large n (typically above ~10,000), this throws a RangeError: Maximum call stack size exceeded. Use iteration for production. JavaScript’s number type loses precision above n = 20.
🌐
Flexiple
flexiple.com › javascript › factorial-javascript
Different methods of finding factorial of a number using JavaScript - Flexiple
March 14, 2022 - In the below example, we make use of the following formula where, ... If you look at it closely and expand the (n-1)! it is the same as what we have discussed at the beginning of this article. function factorial(n) { //base case for 0!
🌐
DEV Community
dev.to › ephraimduncan › recursion-in-javascript-and-react-components-352e
Recursion in JavaScript and React Components - DEV Community
December 13, 2022 - The factorial function calculates the factorial of a given number by calling itself repeatedly with the input number minus one each time. This continues until the input number is 0, at which point the function returns 1 (the base case) and the ...
🌐
Vultr Docs
docs.vultr.com › javascript › examples › find-the-factorial-of-a-number
JavaScript Program to Find the Factorial of a Number | Vultr Docs
September 27, 2024 - Realize that the factorial of n can be defined recursively as n * factorial(n-1), with the base case being factorial(0) = 1.
🌐
YouTube
youtube.com › watch
Factorial using Recursion | JavaScript - YouTube
Check out our courses:Java Full Stack and Spring AI - https://go.telusko.com/JavaSpringAICoupon: TELUSKO10 (10% Discount)DevOps with AWS: From Basics to Ma...
Published   November 8, 2021