When programming in any language.
It's very common to create logic that performs different actions based on one or more conditions.
JavaScript has a variety of conditional statements that will explore in this lesson we'll be exploring
the if else and else if statements 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 will create
a script that converts a student's numerical test score into a letter grade to keep it simple we'll
assume the test was out of 100 marks.
First we need to define the grading system let's say that a score of zero to forty nine equals an F
fifty two sixty nine equals a d seventy to seventy nine equals a C eighteen to eighty nine equals A
B and 90 to 100 one hundred inclusive equals and a
in order to do this.
We need to start by creating our test score variable and assigning a value
called the variable score and we'll assign a value of sixty five for now keep in mind that we'll make
changes to this score to test our script later on.
Next we'll need to start with our first if statement if the score is less than 50.
We want to output an F so start by typing.
If
score is less than 50
you will output an F using the document write method.
If the score is greater than 50 but less than 70 we want to output a D.
Since we're adding a condition to our original if statement we must start this condition with the.
Else if statement
a copy this.
Else if statement because when you create a few others so the next one we need is if the score is greater
than 70 but less than 80.
We want to output a C
this is for if the score is greater than 80 but less than 90 will output a B
and if the score is greater than 90 or equal to 100 we want to output on a
the last thing we want to do is if this score is anything above one hundred we need to display an error
message indicating that the score must be less than 100 because the exam was out of one hundred marks
for this we'll use the L statement the L statement instructs the script on what to do.
If none of the preceding conditions have been met
in I'll go ahead and save this file and previewed in our web browser.
So here we have
d that has been output.
Because our current score we've set it to sixty five.
Now that is greater than 50 in less than 70.
So if we were to change our score let's go ahead and change the score to 81
and in this case it correctly outputs a B because that's over 80 but less and less than 90.
Now let's see what will happen if we create a score above 100
is where our L statement is working.
The score must be less than 100 and so you can go ahead and play with that.
But that's basically how the if else if and l statements were also known as conditional statements.