Hello people I'm new to Javascipt.
Trying to print Fibonacci in Reverse by Recursion. example: RevFib(5) => 3,2,1,1,0
here is the code which works fine.
function fibo(n, a, b)
{
if (n > 0) {
// Function call
fibo(n - 1, b, a b);
// Print the result
console.log(a);
}
}
fibo(5,0,1);
this works fine. but I don't want to output on console. instead I wanted to return a array contain all fibonacci numbers in reverse like [3,2,1,1,0].
I tried to implement it using defining a global array then try to passing that array in fibo() function. It doesn't work. don't know why.
here is the array code:
var arr = [];
function fibo(n, a, b, arr)
{
if (n > 0) {
// Function call
fibo(n - 1, b, a b, arr);
// Print the result
console.log(a ' - ' arr);
arr.push(a);
}
}
fibo(5,0,1);
the output is error:
Uncaught TypeError: arr is undefined
as a newbie in JS. I can't get what went wrong. someone tell whats wrong here. Thanks
CodePudding user response:
You're naming a function parameter called arr. Did you mean to do call fibo like so?:
function fibo(n, a, b, arr) {
if (n > 0) {
fibo(n - 1, b, a b, arr);
console.log(a ' - ' arr);
arr.push(a);
}
}
let arr = [];
fibo(5, 0, 1, arr);
You also don't need arr to be a global variable if you're going to pass it as a function argument. Generally you should avoid globals (unless you have a special use case), because they make code harder to maintain. Passing the array to the fibo function is the right idea.
You could even have a wrapper function to make usage of return types.
function fiboRecurse(n, a, b, arr) {
if (n > 0) {
fiboRecurse(n - 1, b, a b, arr);
console.log(a ' - ' arr);
arr.push(a);
}
}
function fibo(n) {
let arr = [];
fiboRecurse(n, 0, 1, arr);
return arr;
}
console.log(fibo(5));
CodePudding user response:
You are naming a function parameter "arr" as well. The global variable will therefore not be accessible.
CodePudding user response:
You were almost there with your own code. A few tweaks and it runs smoothly:
function fibo(n, a=0, b=1, arr=[]){
if (n > 0) {
fibo(n-1,b,a b, arr);
arr.push(a);
}
return arr
}
const res=fibo(6);
console.log(res)
I used "optional arguments" in the function definition. If they are omitted at calling time they will have the values given in the function definition.