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));