JavaScript for Absolute Beginners 2

In this tutorial, we’re going to write a JavaScript program to print the grade given an exam score.



Other tutorials of this series.

Notes for this tutorial:

Task for this tutorial: Write a JavaScript program to

  • Get an exam score (user input)
  • Print the grade using the mapping in the following table
  • Need to handle incorrect inputs, e.g. non-numbers, out-of-range numbers
Exam score Grade
90-100 A
80-90 (exclusive) B
70-80 (exclusive) C
60-70 (exclusive) D
50-60 (exclusive) E
less than 50 Fail

Get user input

Get user input
1
2
3
4
process.stdin.on("data", function(data) {
const userInputString = data.toString().trim();
//do something
});

Using constant

Using constant
1
2
const num = 123;
num = 321; //error! constant cannot be changed

Convert string to number

Convert string to number
1
const num = parseInt("123"); //num will be a number 123

If-then-else

If-then-else
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const condition1 = false;
const condition2 = false;
const condition3 = true;
const condition4 = false;
if (condition1) {
//do something
} else if (condition2) {
//do something
} else if (condition3) {
//do something (this code block will be executed)
} else {
//do something
}

//and
if (condition2 && condition3) { //evaluated to false
//do something
}

//or
if (condition2 || condition3) { //evaluated to true
//do something (this code block will be executed)
}

//not
if (!condition1) { //evaluated to true
//do something (this code block will be executed)
}

Check if the value is a number

Check if the value is a number
1
2
3
4
const num = 123;
if (isNaN(num)) {
//Not a number
}

Testing

  • normal cases
  • boundary cases
  • error cases

The source code of the program in this tutorial on GitHub.