← Back

Code for calculating factorial

5! -> 5*4*3*2*1

Using Loop

function factorial(n) {
let res = 1,
i;
for (let i = 2; i <= n; i++) res *= i;
return res;
}
factorial(5); // 120

Using Recursion

function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
factorial(5); // 120