You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript递归实现阶乘入门求助:sum未定义错误

Fixing Your JavaScript Recursive Factorial Function

Hey there! Let's break down why you're hitting that ReferenceError and get your factorial function working right.

The immediate issue with your code

The error ReferenceError: sum is not defined pops up because you never declared the sum variable anywhere in your function. Even if you did declare it (like let sum = 1;), using an outer-scoped or global variable for recursion is a bad practice—it would mess up results if you call the function multiple times (e.g., running nFactorial(3) then nFactorial(2) would reuse the existing sum value and give wrong outputs).

How recursive factorial is supposed to work

Recursion relies on a function calling itself with a smaller input, and using its own return values to build the final result. For factorial:

  • Base case (termination rule): 0! and 1! both equal 1—this stops the recursion from looping infinitely.
  • Recursive case: n! = n * (n-1)!—we calculate the factorial of n-1, multiply it by n, and return that value.

Here's the corrected recursive function

function nFactorial(n) {
  // Factorial isn't defined for negative numbers, handle that case
  if (n < 0) return null;
  
  // Base case: stop recursion when n is 0 or 1
  if (n === 0 || n === 1) return 1;
  
  // Recursive case: n! = n multiplied by (n-1)!
  return n * nFactorial(n - 1);
}

// Test it out:
console.log(nFactorial(3)); // Outputs 6, which is correct!

Let's walk through how this works for nFactorial(3)

  1. n=3 isn't a base case, so we return 3 * nFactorial(2)
  2. n=2 isn't a base case, so we return 2 * nFactorial(1)
  3. n=1 matches the base case, so we return 1
  4. Now we work backwards: 2 * 1 = 2, then 3 * 2 = 6—that's our final result!

Alternative: Using an accumulator (if you're curious)

If you want to experiment with an accumulator variable (though the first approach is more straightforward for factorial), you can pass it as a parameter with a default value to avoid external state:

function nFactorial(n, sum = 1) {
  if (n < 0) return null;
  // Base case: when n reaches 0, return the accumulated sum
  if (n === 0) return sum;
  // Pass the updated sum to the next recursive call
  return nFactorial(n - 1, sum * n);
}

The big takeaway here is that recursive functions should depend on their own return values and clear base cases, not external variables. This keeps them predictable and free of unexpected side effects.

内容的提问来源于stack exchange,提问作者user2785628

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:39:59