Recursion is one of the most misunderstood concepts in software development. Truthfully, in modern software development it has been almost completely replaced by iterative control structures (loops). In front-end UI-layer development, it is very rarely used. However, it’s very common that you’ll be asked questions about recursion during an interview. Why? I compare it to airlines hiring Air Force and Navy fighter pilots. No, they’re never going to need to barrel roll a commercial jet-liner but the fact that they understand and know how to do it makes them more complete pilots. Similarly, understanding concepts such as recursion opens up new ways of thinking for engineers.
In its most simple terms, a recursive function is a function which returns a call to itself. Naturally, one has to be careful with this type of construct as it’s easy to create an infinite loop. A typical recursive pattern involves breaking a problem into smaller pieces (such as searching a large data set) rather than performing a process multiple times as in iteration.
A common interview question may involve implementing a factorial function using recursion. Let’s take a quick look at how we could do this:
function fact(x) {
if(x > 1) {
return x * fact(x-1);
} else {
return 1;
}
}
By including a call to itself in the return, the program builds up and subsequently tears down a call stack. Rather than looping over an operation, we’re breaking the problem into smaller pieces until it’s simply returnin the value we passed in.
Drawbacks of Recursion
Now that we have an understanding of how to create a basic recursive function, we need to be able to discuss the drawbacks of this approach. First, in most programming language, the loop control structures (for, while, etc.) are optimized for speed and will (in the vast majority of cases) be faster.
Second, the memory overhead for allocating all of those functions can grow massively; especially in dynamic languages like Javascript. In our above example, if a user called fact(200) we would incur the overhead of creating 200 function instances in memory. You can see that for large operations this will get very heavy.
Stand Out
For the most part in front-end development, you won’t be delving deeply into recursion; but armed with this basic understanding of the topic, you’ll stand out from other candidates who aren’t familiar with a wide array of software engineering concepts.