Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Show message "no score entered" if user inputs a specific number into a prompt

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!