0
var fib = function (n) {
    if (n == 1) {
        return [0, 1];
    } else {
        var s = fib(n - 1);
        s.push(s[s.length - 1] + s[s.length - 2]);
        return s;
    }
}

console.log(fib(5));

In the above code snippet, when I do a debug - after the return s is executed first time control goes back to s.push(s[s.length - 1] + s[s.length - 2]);.

My understanding is that "return" should be the last statement executed in a code snippet.

It will be very appreciated if someone could help me understand this.

Stalin
  • 1
  • this is recursion for you. Before you reached the return statement, you pushed multiple calls to the fib function in the stack. The first hit on return, actually is the end of the last entry in the stack(excluding the n==1 branch which would resolve first). The return in this case resolves the var s = fib(n-1) and then moves to the next entry in the stack where the next instruction is s.push(.... – tstoev Jul 02 '20 at 10:48
  • 1
    Can be thought of as an equation with parentheses (curly, here - "{}"), solved inner-most first. {fib(5) {calls fib(4) {calls fib(3) {calls fib(2) {calls fib(1) just returns [0,1]} pushes (0+1), returns [0,1,1]} pushes (1+1) returns [0,1,1,2]} pushes (1+2) returns [0,1,1,2,3]} pushes (2+3) returns [0,1,1,2,3,5]} – iAmOren Jul 02 '20 at 11:39
  • Thanks for the inputs @tstoev. I am new to Java Script, I never had a thought on the concept of stack. It seems like I need to get more practice around this and stack concepts as well. Appreciate your help very much. Cheers. – Stalin Jul 02 '20 at 23:51
  • if you want to see the recursion, trace the calls (add a console.log statement in the function). The latter is very useful during debugging in general. In this particular case just remember to keep n small, otherwise you will end with too many entries to process,. – tstoev Jul 03 '20 at 07:53

0 Answers0