Skip to content

Instantly share code, notes, and snippets.

@jcolebot
Last active February 24, 2021 18:25
Show Gist options
  • Select an option

  • Save jcolebot/db240b23922fdf83ebca54c7e446e0a5 to your computer and use it in GitHub Desktop.

Select an option

Save jcolebot/db240b23922fdf83ebca54c7e446e0a5 to your computer and use it in GitHub Desktop.
Fibonacci Sequence solution using a for loop in JavaScript. Sequence grows by adding the sum of the two numbers that precede it. Remember to change the value of "n" when calling the function based on how long you want the sequence to be.
function fibonacciGenerator(n) {
var fibArray = []; //create empty array to push sequence into
if (n == 1) {
fibArray = [0]; //sets first element to 0
}
else if (n == 2) {
fibArray = [0, 1]; //sets second element to 1
}
else {
fibArray = [0, 1]; //if n is more than 2, following loop will begin
for (var i = 2; i < n; i++) {
fibArray.push(fibArray[fibArray.length - 2] + fibArray[fibArray.length - 1]); //adds the previous 2 elements together and pushes it into the array.
}
}
return fibArray;
}
fibArray = fibonacciGenerator(n);
console.log(fibArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment