usha
Login
Back to Blog
June 8, 20262 min read72 views

Recursion in JavaScript

The Mirror in the Mirror

Have you ever stood between two mirrors facing each other?

You see yourself. Behind you, another reflection. Behind that, another — getting smaller and smaller until they're too tiny to see, but theoretically going on forever.

Recursion in programming works exactly like this. Except it always stops.

What is recursion?

A recursive function is a function that calls itself. Each time it does, the problem gets smaller. Eventually the problem is so small it solves itself without any more calls — then the answers bubble back up through all the mirrors.

Every recursive function needs exactly two things:

Base case — the condition that stops the recursion. Without this, the function calls itself forever until JavaScript runs out of memory (stack overflow).

Recursive case — the part where the function calls itself with a smaller, simpler version of the problem.

When should you use recursion?

Recursion is most natural when the problem has a recursive structure — when the solution to the whole is built from solutions to smaller versions of the same problem.

It shines in: tree traversal (file systems, the DOM, family trees), sorting algorithms (quicksort, mergesort), mathematical sequences (factorial, Fibonacci), and nested data (parsing JSON, flattening arrays).

For simple iteration? Use a loop. Loops are more readable and more efficient for that job.

The danger: stack overflow

If a recursive function never hits its base case, it keeps calling itself until JavaScript throws a RangeError: Maximum call stack size exceeded. Always write your base case first.

Key takeaways

Recursion is a function calling itself with a smaller version of the problem.

Every recursive function needs a base case — the stopping condition.

Without a base case, recursion runs forever and causes a stack overflow.

Use recursion when the problem naturally breaks into smaller identical sub-problems.

Follow for more backend engineering breakdowns. Drop a comment — what concept should I cover next?

#JavaScript #Recursion #BackendEngineering #SoftwareEngineering #NodeJS

Chat on WhatsApp