Reputation: 13
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;
Upvotes: 1
Views: 190
Reputation: 123026
Try undefined + 1
(a variable not initialized resolves to undefined
) in the console: its result is NaN
(Not a Number), so any next iteration NaN
+ some number will be NaN
.
Alternatively you can use Array.reduce
(see MDN for more on that) to calculate the sum:
function sum() {
// return the sum of all arguments given.
return ([].slice.call(arguments)).reduce(function (a, b) {
return a + b;
});
}
document.querySelector('#result')
.innerHTML = '<code>sum(1,4,3,5,6)</code> => ' + sum(1, 4, 3, 5, 6);
<div id="result"></div>
Upvotes: 0
Reputation: 36743
Leaving answer uninitialized is equivalent to
var answer = undefined;
And since (undefined + any number) is also NaN (not a number) each loop does nothing but keep reassigning answer to NaN
console.log(undefined + 0); => NaN
console.log(NaN + 1); => NaN
console.log(NaN + 2); => NaN
Upvotes: 0
Reputation: 13232
Because you are trying to add a number to an undefined variable this is not possible because you are trying to add a number to answer which isn't a number until you initialize it.
Upvotes: 0
Reputation: 183612
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
.
Upvotes: 1
Reputation: 48837
answer += (arguments[i]);
equals
answer = answer + (arguments[i])
answer
being initially undefined, you actually have
answer = undefined + (arguments[i])
which is a NaN:
alert(undefined + 42);
Upvotes: 0
Reputation: 6268
Simply put: you cannot add to "undefined". The answer is... undefined, or not a number. You can, however, add to zero, so of course you have to initialize the variable to 0.
Upvotes: 2