Choey
Choey

Reputation: 3

Difference between var name; and var name = 0;

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

Answers (4)

Artur P.
Artur P.

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

Sagar Kharab
Sagar Kharab

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

Chris Staikos
Chris Staikos

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

Tiago Alves
Tiago Alves

Reputation: 2316

Because when you use var sumUpArray, sumUpArray is undefined, not 0. undefined + any number will return NaN.

Upvotes: 0

Related Questions