DEV Community

Eulier Gonzalez
Eulier Gonzalez

Posted on

2 2

Recursion, why is helpful but not in JS, ;(

Recursion according to DSA Course from Zero To Mastery is an algorithmn, that allows to define something in terms of itself or a function that call itself.

For example

let multiplyBy5 = (num) => {
  if(num === 1) return 5
  return multiplyBy5(num - 1) + 5
}
Enter fullscreen mode Exit fullscreen mode

As you can see recursion, is useful for repetitive task.
Of courser iterative solutions are way more better for this small problems.
But when you need to traverse a tree or a graph ( something that is wildly uncommon for Js developer )

Or validate a Binary Search Tree.

const isValidBST = function(root, min, max) {
    if(!root) return true

    if( (min && root.val <= min.val) || (max && root.val >= max.val) ) 
        return false

    return isValidBST(root.left, min, root) && isValidBST(root.right, root, max)
};

Enter fullscreen mode Exit fullscreen mode

Recursion offers :

  • DRY Code (Don't repeate yourself)
  • Readability
  • Useful when you don't know how deep a data structure is
  • Solve problems using a divide and conquer approach

Tradeofs:

  • Iterative solution are more efficient, since they don't have additional function call (they don't use the call stack)
  • Space complexity and Recursion are not friends
  • For new developers it's hard to wrap around their minds

To solve the space complexity issue, there is something call:

  • Tail Call Optimization It allows recursion without increasing the call stack

However, and the reason you're here.

Supringsingly, only [Apple Products*](https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation), support this feature.

The others major js enviroment like, Chrome, Firefox, Edge (client side) and node.js (server side) doesn't support and that might never changes.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️