1

I must have missed something stupid but why is sumArray returning undefined ???

<script>

    function sumArray(arr, n, sum){
        if(n == 0){
            console.log( arr[0] + sum ); // log shows 15 as expected
            return  arr[0] + sum;        // the function would return undefined
        }else{
            sum = sum + arr[n-1];
            sumArray(arr, n-1, sum); 
        }
    }

    var arr1 = [0,1,2,3,4,5];
    var result = sumArray(arr1, arr1.length, 0)

    console.log(result); // returns Undefined !!!

</script>
2
  • 4
    you have no return statement in your else. Commented Oct 8, 2013 at 8:03
  • Shit looks like I didn't sleep weel after all ! Thanks a lot ! Commented Oct 8, 2013 at 8:06

1 Answer 1

6

change:

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

to

else{
  sum = sum + arr[n-1];
  return sumArray(arr, n-1, sum); //return the function
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.