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?

5
  • 3
    Did you check what the value of sumUpArray is before the loop in the latter code? Commented Mar 15, 2018 at 16:54
  • 1
    undefined + any number returns NaN Commented Mar 15, 2018 at 16:54
  • 1
    When you use var sumUpArray, its value is undefined. So, if you add 0 to an undefined value, it will be NaN - Not a Number Commented Mar 15, 2018 at 16:54
  • 1
    By default the value of sumUpArray is undefined. When you sum undefined with a number, you are getting NaN. Commented Mar 15, 2018 at 16:54
  • Some examples: stackoverflow.com/a/14977803/1823841 Commented Mar 15, 2018 at 17:00

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.