I want to write a function that returns a number based on the fibonacci rule where each new number returned is based on the sum of the two previous numbers 1, 1, 2, 3, 5, etc. So if the user inputs 4, the output should be 3. And it should work with any number such as 10, 12, 45, etc.
I tried using for loop to create an array but didn't get the results as I had expected. When i++ >= 3 I get NaN instead of 3.
const fibonacci = function(num) {
for (let i = 2; i < num; i++) {
let arr = [0, 1, 1];
let num1 = arr[i];
let num2 = arr[i - 1];
let push;
push = arr.push(num1 + num2);
console.log(arr);
}
};
fibonacci(4);
The problem in your fibonnaci function is that you are declaring arr
inside the for loop. For instance, you are creating a new array on each iteration and thus the index i
will be NaN
pass the first 3 elements.
const fibonacci = function (num) {
let arr = [0, 1, 1]; // Declare before for loop
for (let i = 2; i < num; i++) {
let num1 = arr[i];
let num2 = arr[i - 1];
arr.push(num1 + num2);
console.log(arr);
}
};
fibonacci(4);