This definition and example are both misleading. Definition of tail recursion :
A function call is called tail recursive if, after the function returns, there is nothing to do but return its value.
There is no need for the recursive call to be immediately before the return statement or the last function statement. Example:
function foo(data) { a(data); return b(data); }
In this case, a is immediately before the return , but b is in the tail position.
function bar(data) { if ( a(data) ) { return b(data); } return c(data); }
In this example, both b and c are in the tail position, although b not at the end of the bar function.
In this example, the last thing function performs multiplication before returning
ans = n * rfact(n - 1);
Therefore, this is not a tail recursive function.
An example of a tail recursive function is
factorial1(n, accumulator) { if (n == 0) return accumulator; return factorial1(n - 1, n * accumulator); // The last thing, before return, performed // by factorial1 is to call itself. } factorial(n) { return factorial1(n, 1); }
which can be optimized by the compiler on
factorial1(n, accumulator) { while (n != 0) { accumulator *= n; n -= 1; } return accumulator; }