🚀Debugging Microservices & Distributed Systems

Trevor I. Lasn

Staff Software Engineer & Engineering Manager

4 min read

Recursion Explained In Simple Terms

Understanding recursion through real examples - why functions call themselves and when to use them

Most tutorials explain recursion using factorials or Fibonacci sequences. That’s nice for learning, but you won’t use those in real work. Let’s look at recursion through actual code you might write.

Think of recursion like reading through a thread of Slack comments. You see a message with replies, and those replies have their own replies, and it keeps going deeper. Each level of replies is the same thing - just messages and responses - but each level is dealing with a smaller piece of the conversation.

In programming, recursion works the same way. A function calls itself to handle a smaller version of the same task. Here’s a Slack comment system to see how recursion works.

JavaScript
const thread = {
message: "Should we deploy on Friday?",
replies: [
{
message: "Never deploy on Friday!",
replies: [
{
message: "Unless it's a critical hotfix",
replies: [
{
message: "Even then, wait till Monday",
replies: []
}
]
}
]
},
{
message: "Let's do it Monday",
replies: []
}
]
};
function displayThread(comment, depth = 0) {
// Base case: if there's no comment, stop
if (!comment) return;
// Display the current comment with proper indentation
console.log(`${' '.repeat(depth * 2)}${comment.message}`);
// Handle each reply (recursive case)
comment.replies.forEach(reply => {
displayThread(reply, depth + 1);
});
}
displayThread(thread);

This code would output:

Should we deploy on Friday?
Never deploy on Friday!
Unless it's a critical hotfix
Even then, wait till Monday
Let's do it Monday

That’s all recursion is - a function that calls itself to handle smaller pieces of data. In our example, it’s showing a comment, then showing all its replies, then their replies, and so on.

Every recursive function needs two crucial parts:

  1. Something it’s trying to do (like displaying a comment)
  2. A “base case” that tells it when to stop (when there are no more replies)

Think of it like this: if someone asks you to count all the comments in a Slack thread, you might say “Okay, I’ll count this comment (1), then count all the replies, then count their replies…” That’s recursion - breaking down a big task into smaller, similar tasks.

File Explorers and Directory Trees

The most common place you’ll use recursion is when dealing with files and folders. Think about Windows Explorer or Finder on Mac. They both need to show you files inside folders, which can have more folders inside them, and more folders inside those… you get the idea.

JavaScript
function listFiles(folder) {
const files = [];
function look(dir) {
const items = fs.readdirSync(dir);
items.forEach(item => {
const path = dir + '/' + item;
if (fs.statSync(path).isDirectory()) {
look(path); // Found a folder? Look inside it
} else {
files.push(path); // Found a file? Add it to our list
}
});
}
look(folder);
return files;
}

This function looks in a folder. If it finds a file, it adds it to the list. If it finds another folder, it looks inside that one too.

A Store Category Menu

The category menu in an online store works just like nested folders. Electronics contains Computers, which contains Laptops. Each category can hold more categories inside it.

JavaScript
const menu = {
name: "Store",
categories: [
{
name: "Electronics",
categories: [
{
name: "Computers",
categories: [
{ name: "Laptops", categories: [] },
{ name: "Desktops", categories: [] }
]
},
{
name: "Phones",
categories: [
{ name: "iPhones", categories: [] },
{ name: "Android", categories: [] }
]
}
]
}
]
};
function showCategories(item, depth = 0) {
const spaces = " ".repeat(depth);
console.log(`${spaces}${item.name}`);
item.categories.forEach(category => {
showCategories(category, depth + 1);
});
}
showCategories(menu);

Running this code shows:

Store
Electronics
Computers
Laptops
Desktops
Phones
iPhones
Android

The showCategories function looks at each category and then peers inside it for more categories.

It starts at “Store” and prints it. Inside Store it finds “Electronics”, prints that with some space to show it’s inside Store. This pattern continues - looking inside each category and printing what it finds - until it hits empty categories. The spaces at the start of each line show how deep the category sits in the menu.

Essentially, recursion is just a way to handle nested data - like comments with replies, or folders with more folders inside. Don’t overcomplicate it. If you can break down your problem into smaller, similar problems, recursion might be the right tool for the job.


Related Articles

If you enjoyed this article, you might find these related pieces interesting as well.

Recommended Engineering Resources

Here are engineering resources I've personally vetted and use. They focus on skills you'll actually need to build and scale real projects - the kind of experience that gets you hired or promoted.

Imagine where you would be in two years if you actually took the time to learn every day. A little effort consistently adds up, shaping your skills, opening doors, and building the career you envision. Start now, and future you will thank you.


This article was originally published on https://www.trevorlasn.com/blog/recursion-explained. It was written by a human and polished using grammar tools for clarity.

Interested in a partnership? Shoot me an email at hi [at] trevorlasn.com with all relevant information.