Currently my JSFiddle allows a user to input some exam scores one number at a time and shows the average and total score for the numbers they give. Currently, if they enter -999 into the box, it means they are finished entering numbers and the average and total can be calculated.
How can I edit this to make it so that if the user entered -999 as their first input it displays “No score entered.”?
<script>
function userInput() {
var examScores = 0;
var totScores = 0;
var i = 0;
var scores = [];
while (true) {
examScores = parseInt(prompt("Enter a score or enter -999 when you're finished: "));
if (examScores === -999 && scores.length === 0) {
document.getElementById("scores").innerHTML = "No score entered.";
break;
}
else if (examScores === -999) {
break;
}
else {
scores.push(examScores);
i++;
}
}
for(var i = 0; i < scores.length; i++) {
totScores = totScores + scores[i];
}
document.getElementById("scores").innerHTML = "<h1> The sum of these scores is: "+totScores.toFixed(2)+"<br/> The average of these scores is: "+(totScores/scores.length).toFixed(2);
}
</script>
<h1>Exam Scores</h1>
<h3>Click to enter scores</h3>
<input type="button" value="Enter student scores" onclick="userInput()" />
<div id="scores"></div>
You need to return instead of just breaking the loop.
if (examScores === -999 && scores.length === 0) {
document.getElementById("scores").innerHTML = "No score entered.";
return;
}
Breaking the loop solely will cause the function execution to continue, hence always reaching
document.getElementById("scores").innerHTML = "<h1> The sum of these scores is: "+totScores.toFixed(2)+"<br/> The average of these scores is: "+(totScores/scores.length).toFixed(2);
Since the above line is being executed, your own work will be overwritten. Returning from within the loop would end the execution of the function.