0

In ES6 new features, I cannot understand the "Tail Calls", Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.

function factorial(n, acc = 1) {
    'use strict';
    if (n <= 1) return acc;
    return factorial(n - 1, n * acc);
}

// Stack overflow in most implementations today,
// but safe on arbitrary inputs in ES6
factorial(100000)

I searched but I still cannot understand clearly.

  1. Can anyone explain to me why the old javascript(ES5) will have problems with recursive algorithm?

  2. How the "Tail Calls" avoid the problem?

Alba Hoo
  • 154
  • 8
  • 1
    See if https://en.wikipedia.org/wiki/Tail_call answers your question? – user94559 Jul 17 '16 at 07:30
  • `factorial` can't do anything with the results of its recursive call, because it is its last expression (tail position). Consequently, no stack frame must be preserved. –  Jul 17 '16 at 07:38
  • @smarx yes, it is a duplication of that link, thanks for letting me know. – Alba Hoo Jul 17 '16 at 07:42
  • @LUH3417 is that means that most of time, we should avoid use tail call? I only know this concept today, not very familiar with "tail call", but i think I use it a lot, which probably very risky. – Alba Hoo Jul 17 '16 at 07:48
  • No, tail recursion is great. Try to use it whenever it suits. Sometimes it doesn't work, such as with tree traversal. –  Jul 17 '16 at 09:27
  • @LUH3417 Thanks :) – Alba Hoo Jul 17 '16 at 09:30

0 Answers0