Replace Loops With Recursion

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

i-- wil decrease i but returns the previous value, so you are passing i in the function, without reducing it first.

note that without a return statement also there, the function will return undefined

it is recursion as long the function call itself, so also your second version is recursion

Ok thank you. After you said this > " i-- wil decrease i but returns the previous value"
I remembered something from before. So changed it to countdown(–i) which works :slight_smile:

Thanks for lending me your brain power :smiley:

you still don’t need to change the value of i, as if you need a bit more complex logic there that still need the same value of i, you will have unexpected behaviour

ah i see, okay thanks. I’ll remember that :slight_smile: