-2

Hey so I have this bit of code. my issue is that it doesnt work unless I set sumNum to an integer and I dont understand why.

var sumNum; //var sumNum = 0;

const sumAll = function(startNum, endNum) {
    for(var i = startNum; i<= endNum; i++) {
        sumNum += i;
    }
    return sumNum;
}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
archhmod
  • 69
  • 1
  • 7
  • 2
    If you don't declare the variable as zero you are adding something to `undefined` which results in not-a-number. – Mark Feb 02 '19 at 13:47
  • 1
    Why use a global variable? Use `let sumNum = 0` inside of the function before the loop -- although for this particular case, why not skip the loop entirely and use known mathematical formulas for the sum of all integers in a given range? – John Coleman Feb 02 '19 at 13:49
  • The exercise I'm doing wants me to use a loop. I declared my variable outside of the loop because it i didnt think i'd be able to return it once i had finished the loop – archhmod Feb 02 '19 at 13:56

2 Answers2

3

If you don't define than it is assigned a value undefined implicitly.

and math operation on that will result in NaN

console.log(undefined+1)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Think about what happens when it's not a number. The first statement it appears in is sumNum += i. When you don't set it to a number it's value is undefined, so it calculates sumNum = undefined + i which results in NaN. And after that it's sumNum = NaN + i, which still results in NaN.

To fix it you could check the value before and set it to 0 if it's undefined: sumNum = sumNum || 0 (sets it to 0 when falsy).

But I think you don't even want it to be a global variable, in which case you just need to declare it inside your function (which is better to be declared using the normal syntax)

function sumAll(startNum, endNum) {
  var sumNum = 0;
  for (var i = startNum; i <= endNum; i++) {
    sumNum += i;
  }
  return sumNum;
}

console.log(sumAll(1, 3));
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38