## Who's afraid of recursion?

·   ·  ☕ 2 min read

### What is recursion anyway?

A program calling itself.

### How does it look?

conquerPlanet() {
// infinite loop - there are too many planets to conquer
conquerPlanet();
}


### OK.. how about a practical use case?

Well, I am not quite a ‘theory’ guy. But here you go with the age old problem of calculating factorial.

function getFacty(num) {
if (num > 0) return num * getFacty(num - 1);
else return 1;
}

const result = getFacty(10);
console.log("result", result);


### Why use recursion?

The program looks elegant, doesn’t it?

Recursion is also said to be better at “tree traversal”, a fancy term that represents the internal processing to get to the right data in a repeating task.

### Why not use recursion?

The program just looked fine with our friend, the ‘for’ loop.

const num = 10;
let result = 1;
for (let i = num; i > 1; i-- ){
result = result * i;
}
console.log("result-likey", result);


Or, rewrite using the other 10000 loop types at your disposal.

My opinion of why not to use recursion -

• It is said to be more memory intensive (new stack / instance getting created for each call)
• More CPU
• I just don’t like it (I carry this opinion based on ‘nothing’. Ah, the bane of being a stupid programmer)

### Help, why is this post going on for more than 10 lines..

Or, conclusion
You can be alive without recursion for sure. But be fair - the recursion looks elegant.

Aside: Did you know that you can execute the Javascript scripts (?) outlined above either by putting them in a simple ‘facty.js’ file and executing the file using ‘node’? Or you can say “eff it” and use an online playground like JSComplete?

Stay in touch!
Share on

WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things