I understand that when a variable is declared it is given the value "undefined", but I don't understand why the following code doesn't work (returns NaN):
function sum() {
// return the sum of all arguments given.
var answer;
for (var i = 0; i<arguments.length; i++){
answer += (arguments[i]);
}
console.log(answer);
}
sum(4,5,3,2);
In order to get the correct answer (14), I had to initialize the answer variable:
var answer = 0;
In essence, you're asking why undefined + 5 + 4 + 3 + 2
is NaN
(not a number). The answer is that, when you treat undefined
as a number, it is implicitly converted to NaN
. Any operation on NaN
will, in turn, result in NaN
.