In the Fibonacci sequence, each number after the first two is the sum of the two preceding values:
F(n) = F(n - 1) + F(n - 2)
Enter how many elements you want. The original filename uses “fabonacci”; the mathematical term and page content are corrected to Fibonacci while the URL is retained for compatibility.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>JavaScript Fibonacci Series Demo</title></head>
<body>
<label for="t1">Number of Fibonacci elements</label>
<div class="col-sm-4 px-0"><input type="number" class="form-control" id="t1" min="1" max="200" 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 fibonacciSeries() {
const count = Number(input.value.trim());
if (!Number.isInteger(count) || count < 1 || count > 200) {
output.textContent = "Enter an integer from 1 to 200.";
return;
}
const series = [];
let a = 0n;
let b = 1n;
for (let i = 0; i < count; i += 1) {
series.push(a.toString());
[a, b] = [b, a + b];
}
output.textContent = `Series is: ${series.join(", ")}`;
}
submitButton.addEventListener("click", fibonacciSeries);
</script>
</body>
</html>
The current value is added to the series, then the two running values are advanced together. BigInt keeps later Fibonacci values exact. The demo limits the requested length to 200 so the output remains practical to read.
| 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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.