DEV Community

loading...

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

eulier profile image Eulier Gonzalez ・1 min read

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.

Discussion (0)

pic
Editor guide