Skip to content
Return the Factorial of a number

Return the Factorial of a number

Write JavaScript code to return the factorial of the given number. In case of invalid input undefined will be returned.

// Factorial of a number
function factorial(n) {
  if (n < 0) return undefined;
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result = result * i;
  }
  return result;
}

console.log(factorial(1)); // 1
console.log(factorial(5)); // 120Code language: JavaScript (javascript)
Back to Top
Tags: