Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this tail call optimized function fail with a maximum call stack size exceeded error?

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?

like image 382
Ben Avatar asked Oct 30 '22 12:10

Ben


1 Answers

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);
})();
like image 161
Ben Avatar answered Nov 02 '22 22:11

Ben