“Factorialize a Number”

“Factorialize a Number”
0.0 0

#1

function factorialize(num){
if(num <= 1) return 1;
return (num * factorialize(num-1));
}

factorialize(5);
// return 120

hi! i have doubt regarding "return " . The return statement ends function execution and specifies a value to be returned to the function caller. So return (num * factorialize(num-1)); how is this code working?


#2
function factorialize(num){
    if(num <= 1) return 1;
    
    return (num * factorialize(num-1));
}

Let’s simply track what happens when num = 3. I’ll call factorialize simply f.

#1 ( 3 * f(2) )             // f(2) must return to its caller #1
#2 ( 3 * ( 2 * f(1) ) )     // f(1) must return to its caller #2
#3 ( 3 * ( 2 * (1 * 1) ) ) // At this point, there is no more recursive calls.
#3 ( 3 * ( 2 * (1) ) )     // #3 returning to #2
#2 ( 3 * ( 2 ) )          // #2 returning to #1
#1 ( 6 )                  // #1 returning to the original caller.

In the first step, the return statement ends up calling f(2). To compute 3 * f(2), we must resolve f(2) because it is a function call.

So, the function must wait for f(2) to return. f(2) must return to the caller, function context #1.

The same process goes on until no further call is made to itself.

Then, the rest is each function context returning to previous caller.


#3

You’re right that the return statement ends function execution, however it first evaluates the expression it is to return!

So essentially it is forced to calculate the value of factorialize(num - 1) before the function ends, which progresses as the previous answer says.

See @gunhoo93’s answer for what exactly this entails, and how the values ‘propagate’ back to the topmost function