1

I'm struggeling a bit with recursion and just solved an exercise where you have to sum up all the elements of an array.

function sumArr (para) {

  if (para.length === 0) {
    return 0
  }

  else {
    return para.pop() + sumArr(para)
    
  }
}

When invoked sumArr ( [2,3,4] ) it returns 7, as expected. However, now I changed the function a bit


function sumArr (para) {

  if (para.length === 0) {
    return 0
  }

  else {
    return para.pop() - sumArr(para)
    
  }
}

and when invoked sumArr ( [2,3,4] ) it returns 3, which I can't wrap my head around.

Thanks for reading or even helping me understand recursion a bit better!

5
  • Do you have to use a function to do that calculation or could you use anything in javascripts tool box? like reduce() for example Commented Jul 21, 2020 at 8:36
  • 1
    The pop() method removes the last element from an array and returns that element 4-(3-(2-(0))) = 3 Commented Jul 21, 2020 at 8:38
  • 2
    @fedesc she's trying to learn recursion Commented Jul 21, 2020 at 8:40
  • 1
    It works as expected for addition because it's commutative and associative. Subtraction is not associative: (a - b) - c != a - (b - c) Commented Jul 21, 2020 at 8:41
  • @Barmar Sure. pop() has entered a little confusion there Commented Jul 21, 2020 at 8:43

2 Answers 2

1

You could return a string instead of a calculated value and have alook to the brackets.

function sumArr(para) {
    if (para.length === 0) return 0;      

    let pop = para.pop(),
        temp = `(${pop} - ${sumArr(para)})`;

    console.log(pop, temp);
    return temp;
}

console.log(sumArr([2, 3, 4]));

Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript arrays are passed by reference and value. Using Array.pop mutates the collection, which is leading to side-effects like what you see. Instead, Array.slice as given below will return a copy of the array without the first element:

function sum(arr) {
  if (arr.length) {
    return arr[0] + sum(arr.slice(1));
  } else {
    return 0;
  }
}

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.