
Tail Call Optimization
ECMAScript 6 offers tail call optimization, but many engines do not support or provide this.
When do we say a function qualifies for tail call optimization?
If the last statement in a function body is return statement which contains single function call, qualifies for the tail call optimization. Why does the engine optimize it? The answer is to reduce the call stack.
How does this optimization help?
You get more stack to work with, execution is comparatively fast and allows you to execute more number of iterations before the stack overflow error occurs.
Let's learn how to write a Fibonacci Sequence example in JavaScript with and without the tail call optimization.
Fibonacci Sequence
The Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
Without Tail Call Optimization
function fibonacci(input)
{
if(input <= 1)
return input;
return fibonacci(input - 1) + fibonacci(input - 2);
}
var num = 10;
console.log(`fibonacci(${num}) = ${fibonacci(num)}`);
With Tail Call Optimization
function fibonacci(input, x = 0, y = 1)
{
if (input == 0){
return x;
}
if (input == 1){
return y;
}
return fibonacci(input - 1, y, x + y);
}
var num = 10;
console.log(`fibonacci(${num}) = ${fibonacci(num)}`);
Output (for both the logic):-
fibonacci(10) = 55
![]() | ![]() | ![]() | ![]() |
| Like | Comment | Save | Share |




/api/attachments/att/4/linkedin-null-nan-1200-628.png/linkedin-null-nan-1200-628.100.jpg)
/api/attachments/att/249/webP.gif/webP.100.jpg)