BY Simmi Kava31 May 2021 Edit
JavaScript: Tail Call Optimization

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
BY Simmi Kava
LikeCommentSave
LikeCommentSaveShare
0
Categories
General
YantraJS
Developer Guides
Tutorials
Web Atoms Updates

POPULAR POSTS
17 Mar 2021
LATEST ACTIVITY
Simmi Kava
commented this post.
Simmi Kava
liked this post.
Show more
ARCHIVES
2025
2024
2023
2022
TAGS
javascript (56)
developer (25)
javascriptdeveloper (16)
Xamarin.Forms (16)
Html (14)
typescript (12)
webatoms (12)
xamarin (11)
coding (10)
web-atoms (10)
arrays (9)
android (8)
javascript-developer (8)
csharp (7)
dotnet (7)
css (6)
update (6)
dotnet-standard (5)
function (5)
iOS (5)
methods (4)




Web Atoms: JSX (TSX + TypeScript) for Xamarin.Forms, Hot Reload Your App in Production Environment

PlaygroundSamples Repository