Recursive Factorial in JavaScript

Level 3103 keystrokes

Recursion is when a function calls itself to solve smaller subproblems.

JavaScript code

// Define a recursive function for factorial
1function factorial(n) {
// Base case: factorial of 0 or 1 is 1
2 if (n <= 1) return 1;
// Recursive case: n! = n * (n-1)!
3 return n * factorial(n - 1);
4}
// Calculate 5! = 5 * 4 * 3 * 2 * 1 = 120
5console.log(factorial(5));

Output

120
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 5
  • )× 5
  • ;× 3
  • -× 1
  • .× 1
  • {× 1
  • }× 1
  • *× 1
  • <× 1
  • =× 1

More JavaScript examples at level 3

← JavaScript typing practice