Denisowator Denisowator - 1 year ago 62
Javascript Question

Values show together instead of as a new value

I did an exercise today in college, and it was a JavaScript program to calculate the average score of pupils in a test.

Here is my code:

<!DOCtype html>

<title>While loop</title>

//The total score of all pupils
var total = 0;
//The number of scores
var count = 1;

while (count <= 10) {
grade = prompt("Insert the grade:");
total = total + grade;

var average = +total / 10;
document.write("The average is " + average);



The values I put in are 10-100 going up in 10s. So I put in these 10 values "10, 20, 30, 40, 50, 60, 70, 80, 90, 100" And instead of getting the average, I'm getting all of these values side by side.

What am I doing wrong?

Answer Source

grade = prompt("Insert the grade:"); is the problem. The prompt is taking your input as a string, and in JS, adding two strings just concatenates the values. So parse your inputs:

grade = +prompt("Insert the grade:"); //+ is shorthand for casting to a number

Or use parseInt

grade = prompt("Insert the grade:");
var numberGrade = parseInt(grade);

FYI - all the numbers you're adding have to be integers - else it'll just end up as a string again, example:

10 + 10; //20
10 + "10" //1010
10 + 10 + "10" //2010
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download