Why no javascript engines support tail call optimization?

I recently learned about optimizing tail calls in Haskell. I learned from the following posts that this is not a javascript feature:

Is there something inherent in javascript design that makes tail call optimization difficult? Why is this a core feature of a language like haskell but is only now being discussed as a feature of some javascript engines?

+4


source to share


1 answer


JavaScript call optimization is supported. No browsers implement it, but it fits because the specification (ES2015) is complete and all frameworks will need to implement it. Transpilers like BabelJS, which translate JavaScript to legacy JavaScript, already support it, and you can use it today.

Babel's translation makes it pretty simple:

function tcoMe(x){
    if(x === 0) return x;
    return tcoMe(x-1)
}

      

Converted to:



function tcoMe(_x) {
    var _again = true;

    _function: while (_again) {
        var x = _x;
        _again = false;

        if (x === 0) return x;
        _x = x - 1;
        _again = true;
        continue _function;
    }
}

      

That is, in the while loop.

As for why it was only recently supported, there hasn't been much need from the community to do it before as it is a mandatory language with loops, so in the vast majority of cases, you can write this optimization yourself (as opposed to ML where it is needed. as Bergi pointed out).

+6


source







All Articles