Search code examples
javascripttail-recursiontail-call-optimization

Can JavaScript function call subexpressions be tail calls?


Consider the following return statement:

return f() || g();

The call f() obviously is not a tail call, because the function does not actually return if f() is falsy.

What about the g() part though, is that a tail call? Or do I have to rewrite it like this:

const temp = f();
if (temp) return temp; else return g();

Solution

  • Yes, but it doesn't help in practice.

    According to the standard, g() is in tail position:

    LogicalORExpression : LogicalORExpression || LogicalANDExpression

    Return HasCallInTailPosition of LogicalANDExpression with argument call.

    However, most browsers don't support tail call elimination, and the Chromium team isn't working on it, so you can't rely on tail call elimination in practice no matter how you write your tail calls.