DJ012 DJ012 - 3 months ago 17
Javascript Question

Why is my Javascript for loop concatenating numbers rather than adding?

I'm trying to write a little snippet where prompts ask the user for 5 numbers and computes the total of the numbers.

So far I have this:

var counter, number, total;

for(counter = 0; counter < 5; counter++) {
number = parseFloat(prompt("Enter a number:"));
total += number;
}

document.write("The total is " + total + ".");


However the 'total' returns " " for example, rather than a sum of 15.

How do I fix this?

Thanks in advance!

Answer Source

You should initialize your total var to 0:

var counter, number, total = 0;

for(counter = 0; counter < 5; counter++) {
  number = parseFloat(prompt("Enter a number:"));
  total += number;
}

document.write("The total is " + total + ".");