Reputation: 31
// program to count down numbers to 1
function countDown(number) {
// display the number
console.log(number);
// decrease the number value
const newNumber = number - 1;
// base case
if (newNumber > 0) {
countDown(newNumber);
}
console.log(newNumber);
}
countDown(4);
// output => 4 3 2 1 0 1 2 3
I can't visualize what happens after the if condition. I mean I understand that there is "loop" with countDown(newNumber). But I don't understand why there is the output 0 1 2 3. I know I can put an else keyword, but I'd like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber).
Upvotes: 0
Views: 286
Reputation: 22320
this way ?
countDown( 4 )
// program to count down numbers to 1
function countDown(num)
{
if (num<1) return
console.log(num)
countDown(--num)
}
Upvotes: 0
Reputation: 1135
Your recursive call does not end the execution of the function.
So what happens is that if you call newNumber(2)
it executes the first console.log, logging 2. Then it assigns newNumber
to 1. Then your recursion happens, printing 1. Inside the recursive call newNumber becomes 0, so no more recursion. Instead, the second print inside the recursion prints 0.
Now your recursion returns, and the second print outside of your recursion prints the current value of newNumber
in the non recursive call. And that is 1.
So you get 2 (outside recursion) 1 (inside) 0 (inside) 1 (outside)
Upvotes: 3
Reputation: 63525
You can simplify your function.
function countDown(number) {
if (number > 0) {
console.log(number);
countDown(--number);
}
}
countDown(4);
Upvotes: 1