Arno 2501
Arno 2501

Reputation: 9417

javascript function returns unexpected undefined

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>

Upvotes: 1

Views: 854

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

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
}

Upvotes: 6

Related Questions