Recursion, why is helpful but not in JS, ;(
Eulier Gonzalez
Posted on April 10, 2021
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
}
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)
};
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.
Posted on April 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.