0

I have written the following program in javascript:

function recursiveSum(a) {
  sum = 0;
  for (i=0;i<a.length; ++i) {
      if (typeof a[i] === "number") {
          sum += a[i];
      } else if (a[i] instanceof Array) {
          sum += recursiveSum(a[i]);
      }
  }
  return sum;
}
function arraySum(a) {

    // i will be an array, containing integers, strings and/or arrays like itself.
    // Sum all the integers you find, anywhere in the nest of arrays.

    return recursiveSum(a);
}

And I can't figure out why the result of arraySum([[1,2,3],4,5]) is 6. Why the elements after the first array are not processed?

3
  • 2
    Where is your sum var defined? It may not be local to the function. Commented Oct 9, 2013 at 14:26
  • as soon as you can, type "use strict;" at the beginning of all your js files. It doesn't allow your buggy style global variables without var. Commented Oct 9, 2013 at 14:36
  • 1
    I am a beginner in javascript and was writing code somewhat in association to other languages. I forgot to put var in front of the variables and so my variables are global as the answers suggested. Commented Oct 9, 2013 at 14:37

2 Answers 2

7

You have a problem with Global Variables. You need to use var, it is not optional.

Both sum and i need to be declared with var.

var sum = 0;
for (var i=0;i<a.length; ++i) {
Sign up to request clarification or add additional context in comments.

Comments

4

Your sum and i variables are globals, because you haven't declared them as local to the function. You're falling prey to The Horror of Implicit Globals. It's primarily the i variable that's causing the trouble with your specific input: Since your first entry in a is an array, i gets incremented by the recursive call, and the last two entries in the array are never processed by the outer call. (But if you'd used [1, 2, [3, 4, 5]], the fact the calls share both i and sum would be causing trouble.)

Put var in front of each of them. Also look into using the new strict mode, which would have made that a useful error.

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.