Menu

Post image 1
Post image 2
1 / 2
0

Recursion in 5 Minutes (with examples)

DEV Community·Mohamed Idris·22 days ago
#Zqmq2X8z
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. That is the #1 recursion bug. Concrete: countdown from 3 Easiest possible recursion in JavaScript: function countdown ( n ) { if ( n === 0 ) { // base case console .…

Continue reading — create a free account

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

Read More