Using recursive!

Tell us what’s happening:

how to solve this: Write a recursive function, sum(arr, n) , that returns the sum of the first n elements of an array arr .

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15.

Challenge: Replace Loops using Recursion

Link to the challenge:

A good first step is looking at their example for multiplication and modifying it so that it works for addition, i.e (arr, n - 1) * arr[n - 1] => (arr, n - 1) + arr[n - 1].
Also realize that returning 1 won’t give you the desired outcome for recursing w/ addition.

  function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];

Recursion is tricky to understand. I wrote a blog post about it, sort of deconstructing the process, and the thought process behind it.

I think you need to fix the sintax issues here

you can’t use += on something that is not a variable

but you can use +

arr([n-1) is wrong first because you have mismatched parenthesis, second because to access an element in an array you need to use bracket notation

1 Like