left-icon

ECMAScript 6 Succinctly®
by Matthew Duffield

Previous
Chapter

of
A
A
A

CHAPTER 17

Tail Recursion Calls

Tail Recursion Calls


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.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.