tshi
tshi

Reputation: 13

Why does adding numbers to undefined to result in NaN?

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

Answers (6)

KooiInc
KooiInc

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> =&gt; ' + sum(1, 4, 3, 5, 6);
<div id="result"></div>

Upvotes: 0

Adam
Adam

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

brso05
brso05

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

ruakh
ruakh

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

sp00m
sp00m

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

Ashley Strout
Ashley Strout

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

Related Questions