What is going on?

I am working through the Freecodecamp javascript certificate, and a question to write some JavaScript recursion came up. The bit that has me really curious, is where we ‘return 0;’ when our n is decremented down to 0.

Where is javascript holding our value of return, how does it know to hold that value, I didn’t tell it to… There’s so much here that I just am like, HUH?

I can make this pass by putting return false; or return 0; but you can put any kind of number in the ‘return 19;’ bit and it will add that bit to the current return value. What is going on behind the code here? I’m not even sure what to google to figure this out, what is it?

function sum(arr, n) {
  // Only change code below this line
  if(n <= 0){
    // what's going on HERE --->
    return 19;
  }
  else {
    //console.log(arr[n] + arr[n-1])
    return sum(arr, n-1) + arr[n - 1];
  }
  // Only change code above this line
}

var x = sum([1, 2, 3, 4], 3);
console.log(x)

Hmm. This is a textbook example of a recursive process. The return values are not saved anywhere, rather the computations are withheld until a certain base condition is met: The chain of computations builds up and builds and builds… and then it is reduced again, proceding from the innermost function call to the outermost.

  sum([1,2,3,4], 4)
= sum([1,2,3], 3) + 4
= (sum([1,2], 2) + 3) + 4
= ((sum([1], 1) + 2) + 3) + 4
= (((sum([], 0) + 1) + 2) + 3) + 4       <-- base case: n = 0
= (((0 + 1) + 2) + 3) + 4                    the innermost expression is
= ((1 + 2) + 3) + 4                          evaluated first
= (3 + 3) + 4
= 6 + 4
= 10

I don’t know if this helps… It’s actually more difficult to explain than to work with once you’ve grasped the concept. @zedshaw has a good explanation of recursion in the JavaScript course. There’s also a really nice illustration in this video at around 32:20.

1 Like

I understand recursion. The bit I’m curious about is if I change it to: return 12;,. Instead of return 0, or return false; at the final stage, it will add that number to the final answer of the function call. Why is it adding to my final sum?

I see. That return statement gets fired only in the innermost call: sum([], 0) in my example above. If you change the return value, you replace 0 (which is the neutral element for addition) with something else in the line below. So that value is always added, you only don’t notice it if it is 0. (False is a so called nullish value in JS and evaluates to 0 in the context of mathematical operations.)

1 Like

Ohhhhh! Ok. The false part had me tripped up

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.