Generate the Fibonacci sequence in JavaScript
Fibonacci Sequence
The Fibonacci sequence is a series of numbers where each number (after the first two) is the sum of the two preceding ones. It typically starts with 0 and 1. So the sequence goes:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
JavaScript Example
Below is a JavaScript function that generates the Fibonacci sequence up to a given number of terms:
// Function to generate Fibonacci sequence
function generateFibonacci(n) {
let fibSequence = [0, 1]; // Start the sequence with 0 and 1
for (let i = 2; i < n; i++) {
fibSequence[i] = fibSequence[i - 1] + fibSequence[i - 2];
}
return fibSequence;
}
// Example: Generate the first 10 Fibonacci numbers
const numTerms = 10;
const fibonacciSequence = generateFibonacci(numTerms);
console.log(fibonacciSequence);
Explanation
- Initialization:
- The function
generateFibonacci
takes one parametern
, which is the number of terms in the Fibonacci sequence you want to generate. - It initializes an array
fibSequence
with the first two Fibonacci numbers:0
and1
.
- The function
- Loop:
- A
for
loop starts at index2
and continues until it reachesn
. - In each iteration, the current Fibonacci number is calculated by adding the previous two numbers in the sequence:
fibSequence[i] = fibSequence[i - 1] + fibSequence[i - 2];
- This newly calculated number is then added to the
fibSequence
array.
- A
- Return:
- After the loop finishes, the function returns the complete Fibonacci sequence up to
n
terms.
- After the loop finishes, the function returns the complete Fibonacci sequence up to
- Usage Example:
- In the example provided,
generateFibonacci(10)
generates the first 10 Fibonacci numbers, which are then logged to the console.
- In the example provided,
Output
When you run the code with numTerms
set to 10, the output will be:
[
]This output represents the first 10 terms in the Fibonacci sequence.
Variations
You can modify the generateFibonacci
function to start the sequence with different initial values, limit it to numbers below a certain value, or even generate it recursively for educational purposes.
0 Comments