Hi,
I’m working my way through the JavaScript source and I’m currently at the “Replace loops with recursion” part of the JavaScript course.
I wanted to really understand so got more help from the video.
I took this code that Beau uses to help understand recursion:
function countdown(i) {
console.log(i); if (i <= 1) { // base case
return;
} else { // recursive case
countdown(i-1);
}
}
countdown(5); // This is the initial call to the function.
First of all my question is how come I cannot use countdown(i–) instead?
I guess from previous lessons, it seems to do the same “decrements by 1” but i think its causing an infinite loop.
Second of all, the code above is simple enough but i thought if i were to fiddle around to get the same result, is it still recursion?
like below:
function countdown(i) {
console.log(i);
if (i > 1) { // Recursive case
countdown(i-1);
} else {
return // Base case
}
}
countdown(5);
the second code looks easier to understand to me but if its not exactly the same thing as the first example then i guess, that’d be good to know lol