Home > Enterprise >  JS function recursion
JS function recursion

Time:09-16

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?

Thanks!

CodePudding user response:

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.

CodePudding user response:

The check for whether a variable is defined, and what value it is (whether it's a number, string, object, function, etc) is done at runtime.

When you run this function, it's after the function is defined. Inside of the function call, it looks for a variable called power (which exists at the time it's run; it also has to exist to be able to call it), and that is a function, so it calls that function because of the (base, exponent -1).

This works in every programming language that I know of that has functions.

  • Related