Menu

1 / 2

Recursion in 5 Minutes (with examples)

DEV Community·Mohamed Idris·6 months ago
#Zqmq2X8z
#when#recursion#javascript#software#countdown
Reading 0:00
15s threshold

The one-line definition: a function that calls itself until it hits a stopping condition.

That's it. Everything else is just patterns.

An example: Russian dolls (matryoshka)

You open a Russian doll. Inside is a smaller doll. Open it → another smaller doll inside. Keep opening until you find the tiniest doll with nothing inside. Then you know the answer: "there were 5 dolls."

You could write that as a recipe:

openDoll ( doll ): if doll is empty inside : return 1 ← the stopping condition else : return 1 + openDoll ( inside doll ) ← the function calls itself

Enter fullscreen mode

Exit fullscreen mode

Two ingredients every recursion needs:

Base case — when to stop ( if doll is empty ).

Recursive step — call yourself on a smaller version of the problem ( openDoll(inside doll) ).

If you forget the base case, you recurse forever and crash.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.