Calculate the factorial of a number
Multiply the integers from 1 to n recursively.
function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }
Input & expected output
Input
5Expected output
120The edge case
Input
0Expected output
1Know the limits
- The lab stops at 18: 19! exceeds Number.MAX_SAFE_INTEGER. Use BigInt for larger values.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Calculate the factorial of a number from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Caps n at 18 to stay below Number.MAX_SAFE_INTEGER. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clamp a number to a range — Keep a number inside an inclusive minimum and maximum.
- Round to a number of digits — Apply decimal scaling and JavaScript rounding for display-oriented values.
- Add an ordinal suffix to a number — Append st, nd, rd or th to a positive integer.