DEV Community

Discussion on: Explain Recursion Like I'm Five

Collapse
 
socratesdz profile image
Sócrates Díaz • Edited

Do you know Matryoshka dolls?

Matryoshka

When you open a doll, you find another doll inside, and when you open that one, there's another one inside. The act of doing this is called recursion. Let's write code for that.

function openDoll(doll) {
    if(doll.isEmpty()) {
        return doll;
    }
    openDoll(doll.open());
}
Enter fullscreen mode Exit fullscreen mode

Recursion is a way of doing an operation over a set of values, where each value is related to the previous one, without iterating or using loops.