Recursive functions
In some cases, you want to call the same function from inside the function. It can be a beautiful solution to rather complex problems. There are some things to keep in mind though. What do you think this will do?
function getRecursive(nr) {
console.log(nr);
getRecursive(--nr);
}
getRecursive(3);
It prints 3
and then counts down and never stops. Why is it not stopping? Well, we are not saying when it should stop. Look at our improved version:
function getRecursive(nr) {
console.log(nr);
if (nr > 0) {
getRecursive(--nr);
}
}
getRecursive(3);
This function is going to call itself until the value of the parameter is no longer bigger than 0
. And then it stops.
What happens when we call a function recursively is that it goes one function deeper every time. The first function call is done last. For this function it goes like this:
getRecursive(3)
getRecursive(2)
getRecursive(1)
...