Converting non-tail calls into tail calls

As tail calls are optimized, you must use tail calls whenever possible, instead of non-tail calls. You can optimize your code by converting the non-tail calls into tail calls. Let's see an example of this, which is similar to the previous one:

"use strict";function _add(x, y) {    return x + y; }function add(x, y) { x = parseInt(x); y = parseInt(y); const result = _add(x, y); return result;}console.log(add(1, '1'));

In the previous code, the _add() call was not a tail call, and therefore, two execution stacks were created. We can convert it into a tail call in this way:

function add(x, y){     x = parseInt(x);     y = parseInt(y);     return _add(x, y);}

Here, we omitted the use of the result variable and instead ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.