Tell us what’s happening:
Okay, after reading several forums and writing this out by hand several times, I think I know what’s happening and want to check my knowledge.
The first thing that I had to understand was that n = the number of values in an array
. Did we learn this previously and it just got lost in my brain? I learned this through a forum and not from the wording in the lesson.
The second thing I had to understand was that in this particular type of function, when you say sum(arr, n) the n is telling you how many numbers in the array to add together. Not just add the array plus the n value. Is this a quality within the Math functions?
Third, n acts differently in the two parts of the function (this is where I think I might be wrong, and it just works coincidentally). In the first part return sum(arr, n-1)
n-1 returns a number and not an index. Additionally, the number passed into the function is taken at face value, and NOT as n = the number of values in the array
. In the second part arr[n-1]
returns an index. So if we take one of the test cases sum([2, 3, 4], 1)
we can think of it as
sum([2,3,4], 0)
(because n=1 and not the 3 values in the array, therefore 1-1=0) which tells us sum ZERO of the numbers together. So we have zero at the beginning of the function. For the second half we have arr[0]
. Because the second part of the function is an index, it’s referring to the 0th place in the array, or 2.
If I take an example not in the tests, let’s say sum([4,5,10],3) I would come up with…
([4,5,10], 2) + arr[2] = 19.
Correct?
What happens if the n passed through is more than the number of items in the array? Say… ([2,4,6], 5) would it be as simple as
([2,4,6], 4) + arr[4] = 12? Since arr[4] doesn’t exist and you can’t add more than three numbers for the first half, you just add as many as possible? (Just tried this with console.log and the result was NaN.) Help me understand plz!
Your code so far
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([1],0))
console.log(sum([2,3,4],1))
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Replace Loops using Recursion
Link to the challenge: