1

Im attempting to write this function that returns the sum of all the digits of a given Number

i keep getting "sum is not defined" error and suspect scope to be the issue...

function sumOfDigits(num) {
  // Write your code here!
  let numArr = num,
    output = [],
    sNumber = num.toString();

  for (let i = 0, len = sNumber.length; i < len; i++) {
    output.push(+sNumber.charAt(i));
  }

  for (let x = 0, sum = 0; x < output.length; sum += output[x++]);
  return sum;

}

I'm guessing its a scope issue since i believe that i have defined "sum" to my knowledge

zero298
  • 25,467
  • 10
  • 75
  • 100
Aman
  • 11
  • 3
  • Indeed, `let` is block scoped, so it's not visible outside that loop. – VLAZ Jul 25 '19 at 14:36
  • Remove `, sum = 0` and add `let sum = 0;` as a line above that loop. – Paul Jul 25 '19 at 14:36
  • 1
    Possible duplicate of [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – VLAZ Jul 25 '19 at 14:36

1 Answers1

2

When using let (or const), a variable is scoped to the block it is contained in. So for this code:

for (let x = 0, sum = 0; x < output.length; sum += output[x++]);

... the block is just the for loop. After the for loop completes, x and sum are both out of scope and cannot be accessed. If you want sum to be available in a wider scope, move its declaration outside of the for loop, as in:

let sum = 0;
for (let x = 0; x < output.length; sum += output[x++]);
return sum;
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98