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
outerFunctionbody, first stack frame is pushed onto stack. - Body of
outerFunctionexecutes, return statement is reached. To evaluate the return statement,innerFunctionmust be evaluated. - Execution reaches
innerFunctionbody, second stack frame is pushed onto stack. - Body of
innerFunctionexecutes, 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...