I found this code about recursion online
function countDownRecursive(n) {
if (n <= 0) {
console.log('Hooray')
return
}
console.log(n)
countDownRecursive(n - 1)
}
I am really confused about this code, why does it console.log("Hooray") and then return nothing? Can you explain it to me? Thank you so much.
you returned a null value, the function output type is void. try this
if (n <= 0) {
console.log('Hooray')
return n
}
return in this context means you don't want to continue running the function (similar to break in iterations).
The above recursive function's logic can be converted to this below while logic.
let n = 3;
//iterate until found the while break
while (true) {
//the condition to stop
if (n <= 0) {
console.log('Hooray');
break; //stop `while`
}
console.log(n)
n = n - 1;
}
why does it console.log("Hooray")
Because the function is recursive and when you start with let's say n=1 the function will not print "Hooray" immediately, because the condition:
if (n <= 0)
does not apply i.e. is false.
By the time we reach the recursion:
countDownRecursive(n - 1)
We call the function again with n=0 due to n - 1, the if-statement will evaluate to true and therefore print "Hooray".
and then return nothing
It does not actually return "nothing", even though the return type is void, it returns undefined, which is the default behavior for return you could also write return undefined instead.
When you use return, it will basically terminate or return from the current function. It will jump back into the scope where you did call the function initially.
Hope that clears it up for you.