I am trying to understand recursion by writing a recursive count function. One variation of the function is to count forward and other backward. I understood the backward one but not the forward one because just by changing order of statements in the else block I am able to count forward.
function countforward(num) {
if (num == 0) {
return 0;
}
else if (num == 1) {
return console.log(1);
}
else {
countforward(num - 1);
console.log(num);
}
}
function countbackward(num) {
if (num == 0) {
return 0;
}
else if (num == 1) {
return console.log(1);
}
else {
console.log(num);
countbackward(num - 1);
}
}
The backward function is clear to me because every time the control hits the else block first the number is displayed and it is reduced and called again, but i didn't get the forward function
countisn't defined.count(), which is undefined.count(num - 1);should bereturn count(num - 1);