// Function to calculate the nth Fibonacci number iteratively
function fibonacci(n) {
if (n <= 1) return n;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
let temp = a + b;
a = b;
b = temp;
}
return b;
}
// Calculate the 10th Fibonacci number
let nthFibonacci = fibonacci(10);
code
Fibonacci Sequence in JavaScript
This JavaScript code defines a function fibonacci that calculates the nth Fibonacci number iteratively. The function is then called to calculate and store the 10th Fibonacci number in the variable nthFibonacci. The comments provide explanations for each part of the code.
Recursion
Fibonacci sequence