I recently learned about tail call optimization in Haskell. I've learned from the following posts that this is not a feature of javascript:
- Tail Recursion optimization for JavaScript?
- Are any Javascript engines tail call optimized?
Is there something inherent to javascript's design that makes tail call optimization especially difficult? Why is this a main feature of a language like haskell, but is only now being discussed as a feature of certain javascript engines?
I recently learned about tail call optimization in Haskell. I've learned from the following posts that this is not a feature of javascript:
- Tail Recursion optimization for JavaScript?
- Are any Javascript engines tail call optimized?
Is there something inherent to javascript's design that makes tail call optimization especially difficult? Why is this a main feature of a language like haskell, but is only now being discussed as a feature of certain javascript engines?
Share Improve this question edited May 23, 2017 at 10:29 CommunityBot 11 silver badge asked Jul 7, 2015 at 15:41 asloanasloan 1237 bronze badges 7- 2 I think ES6 will provide it. – ErikR Commented Jul 7, 2015 at 15:44
- Yep, I believe you're correct. I was more wondering why it is the case that it has only now been added as a feature? – asloan Commented Jul 7, 2015 at 15:45
- 1 See this article explaining the difficulties in tail-call optimization. And yes, it will be implemented for sure in ES6. – Mike Cluck Commented Jul 7, 2015 at 15:46
- 3 The vast difference is that TCO is necessary in haskell, while it is just a feature in other languages that adds plexity to the piler. – Bergi Commented Jul 7, 2015 at 15:49
- In addition, massive recursion will also encounter call stack limitation which is very small by default. I think JS (as of ES5) is not primarily aimed for recursion in the past. – TaoPR Commented Jul 7, 2015 at 15:50
1 Answer
Reset to default 10Tail call optimisation is supported in JavaScript. No browsers implement it yet but it's ing as the specification (ES2015) is finalized and all environments will have to implement it. Transpilers like BabelJS that translate new JavaScript to old JavaScript already support it and you can use it today.
The translation Babel makes is pretty simple:
function tcoMe(x){
if(x === 0) return x;
return tcoMe(x-1)
}
Is 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 - to a while loop.
As for why it's only newly supported, there wasn't a big need from the munity to do so sooner since it's an imperative language with loops so for the vast majority of cases you can write this optimization yourself (unlike in MLs where this is required, as Bergi pointed out).