Tail recursion

A variant of recursion where the result of the last expression in the function is also the returned value.


Example

function getLinkedListLength(node) {
  if (!node) {
    return 0;
  }

  // the recursive call is the last expression
  return 1 + getLinkedListLength(node.next);
}

Non-tail Recursion

function reverseLinkedList(node) {
  if (!node || !node.next) return node;

  const reversed = reverseLinkedList(node.next);

  // not tail recursive
  // there are expressions after the recursive call
  node.next.next = node;
  node.next = null;

  return reversed;
}
function fibonacci(n) {
  if (n < 3) {
    return 1;
  }

  // not tail recursive
  // there are multiple recursive invocations, so
  // there is an expression after one of the recursive
  // calls
  return fib(n - 1) + fib(n - 2);
}

External Resources