1
var printRangeUpDown = function(min, max) {
    if (min === max) {
        console.log('condition met ' + min);
        return
    }
    console.log('low to high ' + min);
    printRangeUpDown(min + 1, max);
    console.log('high to low ' + min);
};

printRangeUpDown(4, 10);

logs 4,5,6,7,8,9,10,9,8,7,6,5,4

Can someone explain why the console.log below printRangeUpDown makes it start logging backward? I understand that low will console log 4,5,6,7,8,9,10(base case) ... but I do not understand why console logging below the recursive makes it print 9,8,7,6,5,4 back to min

2 Answers 2

2

Imagine your stack of recursive calls (the call stack). The child function must complete before the parent can continue.

So at the point the base case is reached (i.e. min == max), the first half of each recursive call has been executed and each waits for its child to return.

The base case does not recurse it just returns. Now the second half of each function is executed. Starting with the most recently called (min = 9) and working towards the first to be called (min = 4). This is called LIFO or Last In First Out.

The reason for the values printed is that for each function call the input arguments are preserved until it returns and so what you are seeing is the same values that were printed on the way towards the base case are printed when returning to the first invocation of the function.

If we add a space for each recursive call then it becomes simple to see how the first and last, second and second to last etc. Call match their values.

4,        // first invocation
 5,       // second
  6,      // third
   7,     // fourth
    8,    // fifth
     9,   // sixth
      10, (base case)
     9,   // sixth
    8,    // fifth
   7,     // fourth
  6,      // third
 5,       // second
4         // first invocation
Sign up to request clarification or add additional context in comments.

Comments

0

Because it is a stack (first in last out).

  1. When you call printRangeUpDown(4, 10) from the very beginning, it goes to printRangeUpDown(min + 1, max);, the program will wait for this function to return to go forward.
  2. Program goes to printRangeUpDown(5, 10), same as above, wait for printRangeUpDown(6, 10);.
  3. Program goes to printRangeUpDown(10, 10), finally, the first return.
  4. Then printRangeUpDown(9, 10) will return, because (10, 10) is returned.
  5. Then printRangeUpDown(8, 10) will return, because (9, 10) is returned.
  6. Finally, printRangeUpDown(4, 10) returned.

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.