When a function returns a value, it replaces the function at the same spot it was called. Let’s take a look at a simple function that returns a sum:
function add(a, b) {
return a + b;
}
Now let’s call the function and store its value:
var result = add(1, 5);
When the function add
is finished, it gets removed and the sum is put in its place
var result = 6; // add(1, 5);
This is no different if a function calls another function. Let’s do something a little more complicated:
function subtract(a, b) {
return add(a, -b);
}
The function subtract
uses the function add
, but makes the second term negative. When we call subtract
, it first processes add
.
var result = subtract(6, 1);
// Step 1
function subtract(6, 1) {
return add(6, -1); // must call the add function
}
// Step 2
function subtract(6, 1) {
return 5; // add(6, -1)
}
// Final result
var result = 5; // subtract(6, 1)
There is no difference if we call a function recursively because every function has its own return value. Let’s try this with the function factorialNum2
(which I’m going to rename for sanity’s sake):
var result = factorialNum(3);
// Step 1
function factorialNum(3){
if(3 == 0){ // this is false, skip
return 1
}else{
return 3 * factorialNum(2) // this happens, 3 - 1 = 2
}
}
// Step 2
function factorialNum(2){
if(2 == 0){ // this is false, skip
return 1
}else{
return 2 * factorialNum(1) // this happens, 2 - 1 = 1
}
}
// Step 3
function factorialNum(1){
if(1 == 0){ // this is false, skip
return 1
}else{
return 1 * factorialNum(0) // this happens, 1 - 1 = 0
}
}
// Step 4
function factorialNum(0){
if(0 == 0){ // this is true
return 1
}else{
return n * factorialNum(n - 1) // we don't use this
}
}
Now we go “backwards”. Pay attention to the step number:
// Step 3
function factorialNum(1){
if(1 == 0){ // this is false, skip
return 1
}else{
return 1 * 1 // factorialNum(0) == 1
}
}
// Step 2
function factorialNum(2){
if(2 == 0){ // this is false, skip
return 1
}else{
return 2 * 1 // factorialNum(1) == 1
}
}
// Step 1
function factorialNum(3){
if(3 == 0){ // this is false, skip
return 1
}else{
return 3 * 2 // factorialNum(2) == 2
}
}
var result = 6 // factorialNum(3)
If this makes sense to you, use the same logic to figure out the answer to your second question.