function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
return sum(arr , n-1) + arr[n-1];
}
// Only change code above this line
}
console.log(sum([2,3,4,5],1))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36.
in a more detail manner this is what is doing on the challenge.
function sum(arr, n) {
// Only change code below this line
if( n <= 0 ){
// n in this case is 3 if its true meaning equal and small than 0 then
// will return false. meaning 0. (this is your base case).
return 0;
}
/*
if does not meet the criteria above will call the function itself
and will return the function of sum(arr, n-1). witch is the
first element of the array.
In addition this line of code arr[n-1]; will do the following work.
Lets have this in consideration Example code:
n = 3
array = [2,3,4];
function: sum([2,3,4], 3);
*/
return sum(arr, n - 1) + arr[n - 1];
/*
3 is the n put it in this code line arr[3 - 1]; = arr[2] now this
is the array base index, witch is 4 in the array.
*/
// then we have this arr[2] = 4
// (arr, 3) = + arr[2] = 4
// (arr, 2) = + arr[1] = 3
// (arr, 1) = + arr[0] = 2
// 4 + 3 + 2 = 9
// Only change code above this line
}
var result = sum([2,3,4], 3); //
console.log(result); // Output: 9