-1

Im trying to get a sum of array injected into a function that loops until all the values are added, the console.log right before the "return" logs the right value, meaning the code works, but when I try to use that function with any array it returns "undefined"...

var total = function(arr) {
     console.log(arr);
    if(arr.length > 1) {
      var temp = []
      for(var i=0, len=arr.length-1; i<len; i++) {
        temp.push(arr[i] + arr[i+1]);
      }
      total(temp);
    }
    else {
        console.log(arr.join()); // 48, exectly what I need
      return parseInt(arr.join());
    }
}

var sup = total([1,2,3,4,5]); // undefined

Not completely sure how to debug it..

3
  • 1
    just add return before total(temp);
    – Grundy
    Jul 15, 2015 at 8:33
  • 1
    Because you weren't passing the result of total(temp) to the caller.
    – Dan
    Jul 15, 2015 at 8:39
  • 1
    @AndreKuznetcov that return does not return to the caller of the first invocation of total. That returns to total(temp), which in turn is not returned at all. I suggest you learn about how return works and how recursion works.
    – Dan
    Jul 15, 2015 at 8:42

1 Answer 1

2

If your arr.length is greater than one, you will invoke total with the temporary array, however, you don't do anything with this temporary array - you don't return it, or utilize it in any way, so the intermediate results are lost.

In addition - this is not a self invoking function; it is recursion.

3
  • Well, self-calling function)) temp array is passed to the next cycle of function and at the end is returned?..? Jul 15, 2015 at 8:34
  • Every cycle its creating the new temp array and passing it to the next cycle untill, the array is 1 element long, and then its suppose to return it... Jul 15, 2015 at 8:36
  • 2
    " and at the end is returned" yes, the value is returned from the call to total(temp). However, you do not return the value from total(temp) to the caller, and so the value is lost. You need to add a return before total(temp).
    – Dan
    Jul 15, 2015 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.