Discover why some problems just can't be solved well with loops alone and how recursion unlocks their secrets!
Why Recursion Exists and What Loops Cannot Express Cleanly in DSA Typescript - The Real Reason
Imagine you want to find the total number of files inside folders, including all subfolders, on your computer. You try to count them by opening each folder one by one and adding up the files manually.
This manual counting is slow and confusing because folders can have many layers of subfolders. Using simple loops, you can only go through one level at a time, making it hard to handle folders inside folders without repeating code or getting lost.
Recursion lets you solve this by having a function call itself to handle each subfolder. This way, you can cleanly explore all layers of folders without complicated loops or extra tracking, making the code simpler and easier to understand.
let totalFiles = 0; for (let i = 0; i < folders.length; i++) { totalFiles += folders[i].files.length; for (let j = 0; j < folders[i].subfolders.length; j++) { totalFiles += folders[i].subfolders[j].files.length; } }
function countFiles(folder) {
let count = folder.files.length;
for (const subfolder of folder.subfolders) {
count += countFiles(subfolder);
}
return count;
}Recursion enables you to elegantly solve problems with repeating patterns inside themselves, like nested folders or branching paths, which loops alone struggle to express clearly.
Calculating the total number of comments and replies in a social media post, where replies can have replies inside them, is a perfect example where recursion shines.
Manual looping struggles with nested or self-similar structures.
Recursion uses self-calling functions to handle these nested layers cleanly.
This makes code simpler, easier to read, and less error-prone for complex problems.