Objective
Given the score of a test, output the corresponding grade as per a grade threshold table.
Difficulty
Description
Recently a 100 mark JavaScript test was conducted at a bootcamp teaching modern web technologies.
The test was a 3-hour test with tons and tons of questions on JavaScript and its browser environment. The grade threshold of the test is shown as follows:
Grade | Marks |
---|---|
A | 90 - 100 |
B | 75 - 89 |
C | 60 - 74 |
D | 50 - 59 |
E | 40 - 49 |
In this exercise, you have to ask the user to enter a score that a person obtained in this test, via a prompt input, and then alert back the corresponding grade as per the threshold table shown above.
If the entered score is not a recognizable value, the code must alert 'Invalid value'.
Here's a live example of what you ought to achieve:
New file
Inside the directory you created for this course on JavaScript, create a new folder called Exercise-19-Exam-Grades and put the .html solution files for this exercise within it.
Solution
The input prompt is pretty simple to set up. We call the prompt()
function with the message 'Enter the score:' and then coerce the return value into a number via Number()
.
The final number ought to be stored in a variable since we'll need it later on. Let's call it score
.
The code below accomplishes this task:
var score = Number(prompt('Enter the score:'));
With the score in hand, now we just ought to determine which range does it lie in from the ones shown in the table above, and then determine the grade.And this requires a couple of if...else
statements along with the &&
logical operator to combine multiple conditions together.
The grade can be stored in another variable, let's call it grade
.
Shown below is the complete code:
var score = Number(prompt('Enter the score:'));
var grade;
if (90 <= score && score <= 100) {
grade = 'A';
}
else if (75 <= score && score <= 89) {
grade = 'B';
}
else if (60 <= score && score <= 74) {
grade = 'C';
}
else if (50 <= score && score <= 59) {
grade = 'D';
}
else if (40 <= score && score <= 49) {
grade = 'E';
}
else {
grade = 'Invalid value';
}
alert(grade);
The else
block deals with the case where grade
isn't a recognizable number (i.e. is isNaN
precisely), making the desired alert message.
And this completes this exercise.