Reputation: 3
I want to sum up myArray
where i declared var sumUpArray = 0
. It return the correct sum of myArray
which is 6.
var myArray = [1, 2, 3];
var sumUpArray = 0;
for (i = 0; i < myArray.length; i++) {
sumUpArray = sumUpArray + myArray[i];
}
console.log(sumUpArray);
But when I declared var sumUpArray;
it return NaN
.
var myArray = [1, 2, 3];
var sumUpArray;
for (i = 0; i < myArray.length; i++) {
sumUpArray = sumUpArray + myArray[i];
}
console.log(sumUpArray);
What is the difference between the two declaration of variable?
Upvotes: 0
Views: 220
Reputation: 896
When you declare variable
var sumUpArray;
is the same as
var sumUpArray = undefined;
So you try add integer to undefined results NaN
sumUpArray = sumUpArray + myArray[i];
sumUpArray = undefined + myArray[i]; // NaN
BTW: use let
and const
to declare variables.
Upvotes: 1
Reputation: 369
var name;
is declared but not assigned or initialized or defined and hence is undefined
however var name=0;
is assigned a value '0'. typeof(name) will tell you that both are having different types.
Upvotes: 0
Reputation: 1160
In the first example you declared the variable but didn't assign any value, so it starts out as undefined
. I think you maybe expected it to be auto-assigned to 0, which it does not.
Then you tried to add some numbers to it, but undefined + {anyNumber} = NaN
.
Upvotes: 0
Reputation: 2316
Because when you use var sumUpArray
, sumUpArray
is undefined
, not 0. undefined
+ any number will return NaN
.
Upvotes: 0