Basic JavaScript - Replace Loops using Recursion

I don’t know why but when it comes to return values in function, I always get confused between local and global scope. Now I’m returning values two times in a single function , which is a frustrated bruteforce approach. So please help me out.

let res = 0;
function sum(arr, n) {
  if (n == 0) {
    return res // returning values locally
  }
  else {
    res += arr[n - 1];
    sum(arr, n - 1);
  }
  return res; // returning values globally. What sin I'm commiting here ? pls help. 
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

as i can see your code works perfectly fine: but if you wanted it to be simplified you can use like this:-

function sum(arr, n) {
  if (n == 0) {
    return 0;
  }
  else {
   return  sum(arr, n - 1) + arr[n - 1]; 
  } 
}

Programming is confusing, cut yourself some slack.

…I always get confused between local and global scope

Functions will always return to the scope that called them. If it was called from a global scope, that is where it will return. If function A calls function B, then when function B returns, it will return to function A, the location that called it.

Now I’m returning values two times in a single function , which is a frustrated bruteforce approach.

It is not accurate to say that the first one returns locally and the other globally. They bother returned from where they call.

The first is what we call the “base case,” the case that that says, “OK, we’ve reached the end, time to start returning.”

The second one, notice that it won’t quite reach the return statement because first it has to call sum - it can’t finish until that is done. That is a really important concept, central to recursion.

So, when I make the call from the global scope:

sum([2, 3, 4, 5], 3)

It enters the function. n is 3 so the base case is not met so we go to the else. We store the current sum in res and we call sum([2, 3, 4, 5], 2). This current function cannot finish until that new function call returns. So, we leave that function on the call stack, unfinished and add a new function call to the call stack.

It enters the function. n is 2 so the base case is not met so we go to the else. We store the current sum in res and we call sum([2, 3, 4, 5], 1). This current function cannot finish until that new function call returns. So, we leave that function on the call stack, unfinished and add a new function call to the call stack.

It enters the function. n is 1 so the base case is not met so we go to the else. We store the current sum in res and we call sum([2, 3, 4, 5], 0). This current function cannot finish until that new function call returns. So, we leave that function on the call stack, unfinished and add a new function call to the call stack.

It enters the function. n is 0 … so finally the base case is met. Finally we can return (remember that none of these function calls have been able to return so far). We return the current res, which was 0. That doesn’t actually get used (more on that later) but we finally return.

That call returns so it completes and is removed from the call stack. Control is passed back to the previous function, that can finally finish, so it returns control to the function that called it, so that can finally finish, … all the way down until you get back to the original call that returns (finally) to the original scope.

Yes, it is weird. Yes, it is confusing. Unfortunately this is a terrible example of when to use recursion, but in truth they all are, because the cases where recursion makes sense can get really complicated.

Now, this:

  else {
    res += arr[n - 1];
    sum(arr, n - 1);
  }
  return res; 

is a little clunky. And really, you don’t need that variable res - which you shouldn’t be using global variables anyway. In reality, you don’t need a variable because the call stack will store the state of the function call. This would be a more typical implementation:

function sum(arr, n) {
  if (n === 0) {
    return 0
  } else {
    return sum(arr, n - 1) + arr[n - 1];
  }
}

That’s doing the same thing, just without a global variable. It’s just storing it in its incomplete state on the call stack.

Don’t worry if this is confusing. It’s confusing for everyone. And people often put too much importance on recursion, imho. It is a very powerful tool but is really only useful on a small set of problems, which many web developers may never even face. True, it is a good workout for your coder brain, and it sometimes comes up on interviews, but don’t freak out if it takes a while to fully grasp this. I’ve worked with more than a few developers that can’t remember how to write a recursive function. I’ve only written one in my professional career.

I might recommend youtube videos. I think how the call stack works is a largely visual thing - if you can find one with good graphics, that might help.

1 Like

@garry2090 and @aynuman19, I wrapped your code in [spoiler][/spoiler] tags since those are working solutions to curriculum challenges.

Thankyou @kevinSmith

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.