Skip to content Skip to sidebar Skip to footer

Javascript Variable Initialization Shows Nan

function sumArray(numbers){ var sum; for(var i in numbers){ sum += numbers[i]; } return sum; } console.log(sumArray([1,2,3,4,5])); Hi all, The outcome is NaN. Howev

Solution 1:

when you create var sum; it's value is undefined [default]

so when you keep adding to undefined you get NaN [Not a Number]

but if you initialize as var sum=0;

then you are adding numbers to 0 so you get correct output

try

console.log(undefined+1); you get NaN but

if you do

console.log(0+1); then you get 1

Solution 2:

When a variable is declared within current scope, it is initialized with undefined value.

var sum; // is initialized with undefined 

In the for loop, the addition sum += numbers[i] is actually doing an undefined + 1 operation. Because both operands are not string types, they are converted to numbers:

  1. undefined + 1
  2. NaN + 1
  3. NaN

Please check this article for more info about the addition operator (example 7).

Of course, to solve this problem just initialize it with 0:

var sum = 0;

Also I would sum the items simpler:

var sum = [1,2,3,4,5].reduce(function(sum, item) { 
  returnsum + item; 
});

Solution 3:

This is because you have not initialized sum. So sum+ will try to add to undefined.

functionsumArray(numbers){
      var sum=0;      // sum="" if you want output as 12345for(var i in numbers){
          sum += numbers[i];
      }
      return sum;
    }

console.log(sumArray([1,2,3,4,5]));

jsfiddle

Solution 4:

The reason behind is very clear. When JavaScript finds any "undefined" or "unexpected" error then it returns NaN.

Where else in your second condition where you added sum=0 ,it already made a value of it then what ever you did it was addition to that value.

Post a Comment for "Javascript Variable Initialization Shows Nan"