function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
factorial(5); // 120Factorial uses recursion: multiply n by factorial(n-1) until the base case n<=1.
Factorial of a number n (written as n!) is the product of all positive integers less than or equal to n.
5! = 5 Γ 4 Γ 3 Γ 2 Γ 1 = 120
0! = 1 (by definition)
This is a classic example of recursion: the base case is n β€ 1, and the recursive case is n Γ factorial(n-1).
function factorial(n: number): number {
// Return n!
}
factorial(5) // 120
factorial(0) // 1