# ES6 Trampoline Function

In this tutorial, we will mainly focus on the Trampoline function that appeared first in ES6(ECMAScript 6). We will start with the discussion of the Trampoline function. Need of using the Trampoline function. Advantages and disadvantages of using the Trampoline function.

Now, let’s see the Trampoline function.

## What is a Trampoline Function?

The trampoline is just a mechanism for optimizing recursion and preventing stack-overflow errors in languages that do not provide tail call optimization, such as JavaScript ES5. To overcome this problem of tail call optimization, trampoline was introduced in ES6 version.

A trampoline function is essentially a loop that wraps around our recursive function. It calls the recursive code bit by bit until it no longer generates recursive calls. If the trampoline function is so beneficial, then what exactly was the problem with recursion? Let’s see the same in the next section of this article.

## The problem of using recursion

Firstly, Let’s see what recursion is. Recursion is a process in which we calculate any result value using the same function but by performing numerous distinct function calls controlled by the Stack data structure. Recursion simplifies the code and, for larger quantities, solves the solution piece by piece.

The issue with ordinary recursion is that each recursive call increases a stack item to the call stack, which can be viewed as a call pyramid. Here's an example of recursively calling a factorial function −

(factorial 4)
(* 4 (factorial 3))
(*4 (*3 (factorial 2)))
(*4 (*3 (*2(factorial 1))))
(*4 (*3 (*2(*1(factorial 0)))))
(*4 (*3 (*2(*1(1)))))
(*4 (*3 (*2(1))))
(*4 (*3 (2)))
(*4 (6))
24


Here's a stack visualization in which each vertical dash represents a stack frame −

					—|—
—|—		—|—
—|—				—|—
—|—						—|—
—|—								—|—


The issue is that the stack has a finite size, and piling up these stack frames can cause the stack to overflow. A bigger factorial calculation would overflow the stack depending on its size. As a result, regular recursion in C#, JavaScript, and other languages could be deemed risky.

This problem of overflowing the stack can be solved using tail recursion. Now, let’s have a word on the concepts of tail recursion.

## Why Trampoline Function?

Before jumping on trampoline function, let’s see these concepts of recursion, tail recursion in details with coded examples.

What exactly is tail recursion? In essence, it does a jump and reuses the context of the previous recursive call, so there is no additional memory cost, rather than invoking the recursive function as the return statement.

This implies that instead of memory consumption steadily increasing with each recursive call, memory usage will stay constant as long as we employ appropriate tail recursion in our recursive functions. For instance, the memory use of a correctly implemented tail recursive implementation of the factorial function can appear like this.

For better understanding let’s find the factorial of a number using both recursion and tail recursion.

## Using Recursion

### Example

<html>
<body style = "text-align: center; font-size: 20px;">
<h2>Using Recursion</h2>
Enter a number: <input id = "digit">
<br><br>
<button onclick = "factorial()"> Factorial </button>
<p id = "result"></p>
<script>
function fact(num) {
if (num == 0) {
return 1;
}
else {
return num * fact( num - 1 );
}
}

function factorial() {
var num = document.getElementById("digit").value;
var fx = fact(num);
document.getElementById("result").innerHTML="The factorial of the number " + num + " is: " + fx ;
}
</script>
</body>
</html>


As seen above, each factorial call is first executed. Only then is the whole number being multiplied. We are altering the function to take the result as a second argument in order to convert it to tail recursion.

## Using Tail Recursion

### Example

<html>
<body style = "text-align: center; font-size: 20px;">
<h2>Using tail recursion</h1>
Enter a number: <input id = "digit">
<br><br>
<button onclick = "factorial()"> Factorial </button>
<p id = "result"></p>
<script>
function fact(num,result=1) {
if(num === 1) {
return result;
} else {
return fact(num - 1, result * num);
}
return result;
}

function factorial() {
var num = document.getElementById("digit").value;
var fx = fact(num);
document.getElementById("result").innerHTML="Thefactorial of the number " + num + " is: " + fx ;
}
</script>
</body>
</html>


This type of execution is more efficient since it needs fewer actions and objects on a stack.

## Using Trampoline Function

### Example

<html>
<body style = "text-align: center; font-size: 20px;">
<h1> Using Trampoline Function </h1>
Enter a number: <input id = "digit">
<br><br>
<button onclick = "factorial()"> Factorial </button>
<p id = "result"></p>
<script>
const tram_fn = (fx) => (...arguments) => {
let result = fx(...arguments);
while (typeof result === 'function') {
result = result();
}
return result;
};

const sumCalculation = (num, sum = 1) => {
return num === 1 ? sum : () => sumCalculation(num - 1, sum * num);
};

function factorial(){
var num1 = document.getElementById("digit").value;
const sumCalculate = tram_fn(sumCalculation);
document.getElementById("result").innerHTML="The factorial of the number " + num1 + " is: " + sumCalculate(num1);

}
</script>
</body>
</html>


This trampoline method is essentially a helper function for implementing Tail Recursion. This converts all nested function calls into a sequential number of function calls, allowing us to avoid a stack overflow issue.

The trampoline function simply wraps the recursive code within the loop and calls that recursive function piece by piece until no recursive calls remain.

## Conclusion

In this article, we discussed the concept of trampoline function. We started with the introduction of trampoline function, compared it to tail call recursion or optimization with various coded examples. Hope you learned and enjoyed it well.