CHAPTER 17
ES6 offers tail call optimization (TCO), where you can make some function calls without growing the stack. This is extremely useful in recursive and functional programming usage in JavaScript.
Let’s look at an example:
Code Listing: 210
function factorial(n, acc = 1) { 'use strict'; if (n <= 1) return acc; return factorial(n - 1, n * acc); } // Stack overflow in most implementations today, // but safe on arbitrary inputs in ES6 factorial(100000);
|
It is important to note that you must be in strict mode for this optimization to work.
Also notice that the last thing to happen in the factorial function is that it returns a value using a call to itself. This is one of the key precepts of functional programming, and most functional programming languages do not incur stack overflow when dealing with recursion.
To summarize, if the last thing that happens before the return statement is the invocation of a function that does not need to access any of the current local variables, the interpreter specified by ES6 will optimize that call by reusing the stack frame.
Note: This will not likely receive optimization until our browsers have an ES6 interpreter in place.