1

I implemented the following recursive JS function to get the the sum of elements in a array. This function works fine, when input [1,2,3] it returns 6, which is OK.

function sumOfNumbers(array) {
    if (array.length == 1) {
        return array[0];
    } else {
        last = array.length - 1;
        return array[last] + sumOfNumbers(array.slice(0, last));
    }
}

However, when changing the order of the sum to:

    return sumOfNumbers(array.slice(0,last)) + array[last];

It returns 5 for [1,2,3]. Does anybody knows why?

2
  • Why are you doing this recursively anyway? Wasted memory, just use a loop. Commented Apr 9, 2014 at 16:51
  • 1
    Nit, I am studing recursivity algorithms Commented Apr 9, 2014 at 18:02

1 Answer 1

3

Because the variable last is global, and you're changing it with your call to sumOfNumbers(array.slice(0,last)), before this part: array[last] sees it.

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

1 Comment

It is actually true, thank you! I changed to var last and works well in any order.

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.