TAIL CALL OPTIMIZATION
The ECMAScript 6 specification also introduced a memory management optimization that allows the JavaScript engine to reuse stack frames when certain conditions are met. Specifically, this optimization pertains to “tail calls”, where the return value of an outer function is the returned value of an inner function, as follows:
function outerFunction() {
return innerFunction(); // tail call
}
Prior to the ES6 optimization, executing this example would have the following effect in memory:
- Execution reaches
outerFunction
body, first stack frame is pushed onto stack. - Body of
outerFunction
executes, return statement is reached. To evaluate the return statement,innerFunction
must be evaluated. - Execution reaches
innerFunction
body, second stack frame is pushed onto stack. - Body of
innerFunction
executes, and its returned value is evaluated. - Return value is passed back to
outerFunction
, which in turn can return that value. - Stack frames are popped off the...