More

# Lecture Notes

### Course: Web Development Masterclass

#### Lecture: JavaScript Conditional Statements

When programming in any language, it is very common to create logic that performs different actions based on one or more conditions.

JavaScript has a variety of conditional statements that we will explore in this lesson:

These statements allow us to execute an action contained within a block of code, if certain conditions are met.

Let's take a look at how this works, with a simple example.

We will create a script that converts a student's numerical test score into a letter grade. To keep it simple we will assume the test was out of 100 marks.

First we need to define the grading system.

0 - 49 = F
50 - 69 = D
70 - 79 = C
80 - 89 = B
90 - 100 = A

In order to do this, we need to start by creating our testScore variable, and assigning a value.

`var score = 65;`

Keep in mind that we will make changes to this score, to test our script out later on.

• If the score is less than 50, we want to output an F.

• If the score is greater than 50 but less than 70 we want to output a D
Since we are adding a condition to our original if statement, we must start this condition with the else if statement.

• If the score is greater than 70 but less than 80 we want to output a C

• If the score is greater than 80 but less than 90 we want to output a B

• If the score is greater than 90 or equal to 100 we want to output an A

• Lastly, if the score is anything above 100, we need to display an error message, indicating that the score must be less than 100. For this we will use the else statement.
The else statement instructs the script on what to do, if none of the preceding conditions have been met.

Final Script:

``` <!DOCTYPE html> <html> <body> <script type="text/javascript"> var score = 81; if ( score < 50 ) { document.write("F"); } else if ( score < 70 ) { document.write("D") } else if ( score < 80 ) { document.write("C") } else if ( score < 90 ) { document.write("B") } else if ( score < 100 ) { document.write("A") } else { document.write("Score must be less than 100"); } </script> </body> </html> ```