Conditional statements are statements that test a condition or conditions to see if they are true or false. They are commonly known as if-then or if-then-else statements.
If the conditions are true then the code will perform a certain action, else if they are false the code will perform a different action. Conditional statements are often used with operators to test the conditions.
In JavaScript there are the following types of conditional statements:
Type | Description |
---|---|
if |
For testing a condition (or conditions) and running a piece of a code if the condition is true. |
else if | For testing other conditions and running a piece of code if the previous conditions are false (not true). |
else | For running a piece of code if all the previous conditions are false (not true). |
if
is correctIf
is not correctIF
is not correct
The if
statement tests if a condition or conditions are true and runs a specific piece of code if they are true.
For example the following if
statement tests if the person's age is less than 18 and if that condition is true, then it runs some code to set the price of the ticket for the movie.
if (personAge < 18){
price = 5.99
}
Now let's check 2 conditions in an if
statement. As well as checking the person's age, we are also going to check that they're old enough to watch the movie.
if (personAge < 18 && personAge >= movieMinimumAge){
price = 5.99
canWatchMovie = true
}
&&
is the AND operatorIf we want to run different pieces of code depending on which conditions are true then we use else if
statements.
In the following example we have added an else if
statement to check if the person's age is greater than or equal to 18.
if (personAge < 18 && personAge >= movieMinimumAge){
price = 5.99
canWatchMovie = true
} else if (personAge >= 18){
price = 7.99
canWatchMovie = true
}
The else
statement is used if we want to run a different piece of code if all the above if
and else if
statements are false.
In the following example we have added an else
statement to run code to prevent the person from buying the movie ticket as they are under 18 and not older than the minimum age for the movie.
if (personAge < 18 && personAge >= movieMinimumAge){
price = 5.99
canWatchMovie = true
}else if (personAge >= 18){
price = 7.99
canWatchMovie = true
}else{
canWatchMovie = false
}