Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS function recursion

This is a beginner’s question but I’m not being able to understand the logic behind this:

function power(base, exponent) {
    if (exponent == 0) {
        return 1;
    } else {
        return base * power(base, exponent -1);
        }
    }

When running a console log we get
console.log(power(2, 3));
-> 8

My questions are:
This is running the return line (exponent not being 0), however (on that same line), how can we multiply the base (which on that example is number 2) by the power function which hasn’t been defined.
Technically it would be like this, right?
2 * power(2, 3 – 1)
But if power hasn’t been defined…what will that (power) part do?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

For recursion you need to understand a concept of "scope". Every time you reach a new call to power() within the function, you enter a new scope back at the beginning of the function. When this new function is able to finish execution and return its value, it will return it back to the original line in the function (line 5 in this example). So, in this example, calling with power(2, 3) the call stack will look like this

from top to bottom, as we descend down layers into new scopes, from the original scope outside the function (scope 1)

scope 1: power(2, 3)
scope 2: return 2 * power(2, 2)
scope 3: return 2 * power(2, 1)
scope 4: return 2 * power(2, 0)
scope 5: return 1

then, once we actually have our return value of 1 from the bottom scope, the scopes can start to resolve, and the value ‘bubbles up’ from the bottom scope, back to the top to give us our final answer.

scope 1 (final answer): 8
scope 2: 2 * 4
scope 3: 2 * 2
scope 4: 2 * 1
scope 5: 1

until we are finally left again with only scope 1, with our final answer of 8. Hopefully this makes sense. If you actually use a debugger and step through the program execution, you can see this happening in real time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading