0

this maybe is not the biggest challenging problem but I've got curious about it. I did a simple code just to get the Fibonacci value based on the user input without recursion and works just fine. Very simple code:

function fib(n) {
    
    let fibArray = [0,1];
    
    let count = 0;
    while(fibArray.length <= n){
        
        let previous = fibArray[count + 1];
        
        let beforePrevious = fibArray[count];
        
        fibArray.push(beforePrevious + previous);
        
        count++;
    }
    return fibArray[n];
} 

But the moment I tried to make it as a recursive function, the result is undefined, even if the value is not.

function fib(n, count = 0, fibArray = [0,1]){

    if(fibArray.length - 1 === n){
        return fibArray[n];
    }

    if (fibArray.length <= n ) {
        
        let previous = fibArray[count + 1];
        
        let beforePrevious = fibArray[count];
        
        fibArray.push(beforePrevious + previous);

        count++;
    }

    fib(n,count, fibArray);
    
}

2 Answers 2

2

Just add a return statement in the last line.

return fib(n,count, fibArray);
Sign up to request clarification or add additional context in comments.

Comments

2

The code is ok, you just need to add a return:

function fib(n, count = 0, fibArray = [0,1]){

    if(fibArray.length - 1 === n){
        return fibArray[n];
    }

    if (fibArray.length <= n ) {
        
        let previous = fibArray[count + 1];
        
        let beforePrevious = fibArray[count];
        
        fibArray.push(beforePrevious + previous);

        count++;
    }

    return fib(n,count, fibArray);
    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.