Reputation: 27
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.
Upvotes: 0
Views: 127
Reputation: 1286
Let's do it with an example. This is the hierarchy of the calls when n = 5
countDownRecursive(5) // "5"
countDownRecursive(4) // "4"
countDownRecursive(3) // "3"
countDownRecursive(2) // "2"
countDownRecursive(1) // "1"
countDownRecursive(0) // "Hooray" because n == 0, we execute the return statement
end of countDownRecursive(0) because of return
end of countDownRecursive(1) because reaching the end
end of countDownRecursive(2) because reaching the end
end of countDownRecursive(3) because reaching the end
end of countDownRecursive(4) because reaching the end
end of countDownRecursive(5) because reaching the end
The returns statement tells the program to stop calling itself
Upvotes: 1
Reputation: 4062
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.
Upvotes: 1
Reputation: 15540
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;
}
Upvotes: 2
Reputation: 348
you returned a null value, the function output type is void. try this
if (n <= 0) {
console.log('Hooray')
return n
}
Upvotes: 2