Factorial of an Input Number in JavaScript

Table of Contents

What Is a Factorial? Top ↑

The factorial of a non-negative integer n, written n!, is the product of all positive integers from 1 through n. For example, 5! = 1 × 2 × 3 × 4 × 5 = 120. By definition, 0! = 1.

Calculate a Factorial Top ↑

The original input → Submit → output facility is retained. This modern version uses BigInt so integer factorials remain exact instead of quickly exceeding the safe-integer range of normal JavaScript numbers.

Output here

Complete Working Source Top ↑

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>JavaScript Factorial Demo</title></head>
<body>
<label for="t1">Enter a non-negative integer</label>
<div class="col-sm-4 px-0"><input type="number" class="form-control" id="t1" min="0" max="500" step="1"></div>
<button type="button" class="btn btn-primary btn-sm mt-2" id="b1">Submit</button>
<div id="d1" class="alert alert-success mt-3" aria-live="polite">Output here</div>
<script>
const input = document.getElementById("t1");
const output = document.getElementById("d1");
const submitButton = document.getElementById("b1");

function showFactorial() {
  const value = input.value.trim();
  const number = Number(value);

  if (!Number.isInteger(number) || number < 0 || number > 500) {
    output.textContent = "Enter an integer from 0 to 500.";
    return;
  }

  let factorial = 1n;
  for (let i = 2n; i <= BigInt(number); i += 1n) {
    factorial *= i;
  }

  output.textContent = `Factorial of ${number} is: ${factorial}`;
}

submitButton.addEventListener("click", showFactorial);
</script>
</body>
</html>

Limits and Edge Cases Top ↑

Factorial is defined here for non-negative integers. The demo limits input to 500 to avoid creating excessively large output in the page. Negative integers and decimal values are rejected.

Number.isInteger()Check whether a parsed value is an integer.
parseInt()Convert a string to an integer where that conversion is appropriate.

Next lower value of any decimal number JavaScript Basic JavaScript variable

JavaScript Math Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer