5

This function should be tail call optimized.
To my knowledge, current browsers (Chrome, even tried it on Canary) should optimize it yet I get an error for this run:

function die(x, s) { 
  return x === 0 ? s : die(x-1, s+1);
}
die(100000, 0);

The error:

VM369:1 Uncaught RangeError: Maximum call stack size exceeded

Or did I get something wrong?

Ben
  • 10,020
  • 21
  • 94
  • 157
  • Yes. JavaScript does not support tail recursion yet. AFAIK only Webkit / Safari TP has implemented this. http://kangax.github.io/compat-table/es6/ – Jared Smith Feb 09 '17 at 18:00
  • Does this need `enable-javascript-harmony`? https://bugs.chromium.org/p/v8/issues/detail?id=4698 – Josh Lee Feb 09 '17 at 18:04
  • 1
    Explained here: http://stackoverflow.com/questions/31273281/why-do-no-javascript-engines-support-tail-call-optimization and http://stackoverflow.com/questions/41666751/tail-recursion-in-nodejs – jfriend00 Feb 09 '17 at 18:05
  • @JaredSmith: Your statement is confusing. TCO is part of the spec, so JavaScript definitely supports it. Not every has implemented it though. – Felix Kling Feb 09 '17 at 21:15
  • @FelixKling I thought there was some rehashing going on as to whether or not it would require opt-in syntax after they got push-back from the vendors. IIRC chakra in particular noticed a significant performance *regression* from trying to implement. – Jared Smith Feb 09 '17 at 21:28
  • @JaredSmith: Sure, [but it's still part of the spec](http://www.ecma-international.org/ecma-262/7.0/#sec-tail-position-calls). – Felix Kling Feb 09 '17 at 21:32

1 Answers1

2

Solved it within 5 minutes of posting, it might be interesting to learn so I'll post the answer:

Tail calls are optimized in strict mode only, so this works: (If running in chrome make sure experimental Javascript is enabled under chrome://flags)

(function () {
  "use strict";
  function die(x, s = 0) { 
    return x === 0 ? s : die(x -1, s + 1);
  }
  return die(100000);
})();
Ben
  • 10,020
  • 21
  • 94
  • 157