Writing Conditional Statements In JavaScript
Conditional statements are an essential building block of any program.
In this lesson we'll break down everything you need to know about conditionals, including the different kinds and how to use them.
We will cover:
What is a conditional statement?
Conditional statements are used to perform different actions depending on different conditions.
An example might be that we want to run different blocks of code based on whether an answer is true or false, or whether an age is greater than, less than, or equal to 67.
JavaScript features the following types of conditional statements:
- if
- else
- else if
- switch
Let's take a look at each one of these in depth.
if
We use if
statements to test a condition and execute code when that condition is true
. An if
statement has the following syntax:
if (someCondition) {
// Run this code!
}
If the condition is not true
, the code within the if
block will not be executed and the program will continue on.
Let's say we wanted to check if someone is legally allowed to learn to drive a car based on their age:
const age = 18;
if (age >= 17) {
console.log('Allowed to drive');
}
In the above example we declare the person's age, and then check if their age is greater than or equal to 17
.
If the condition evaluates to true
, they're allowed to drive, so the code within the curly braces is executed and the console statement is printed.
On the other hand, if the condition evaluates to false
(i.e. the person is younger than 17 and they're not allowed to drive), the code within the curly braces is not executed:
const age = 16;
if (age >= 17) {
console.log('Allowed to drive');
}
When we run the above code, the console statement is not printed to the terminal, because the age does not meet the condition.
else
In many cases we need to run a different block of code if the condition evaluates to false
.
We can perform this using the else
statement. An else
statement can only follow an if
statement - it cannot be written in isolation.
Let's build on our previous example by adding an else
statement. This block of code will be executed if the person's age is less than 17:
const age = 16;
if (age >= 17) {
console.log('Allowed to drive');
} else {
console.log('Not allowed to drive');
}
As 16 is less than 17, the condition evaluates to false
so the code within the else
block is run and Not allowed to drive
is logged to the terminal.
In this way, one of the blocks will always be executed depending on the result of the condition.
if/else
statements are used when you only need to decide between two conditional states i.e. there are only two blocks of code to potentially run.
else if
Sometimes a problem requires more complex logic, where we need to execute different code for more than two conditions. In these scenarios we need to utilise if
, else if
, and else
statements.
For example, what if we need to discern what type of vehicle a person can drive depending on their age? We could write a set of conditional statements that look like this:
const age = 18;
if (age === 16) {
console.log('Allowed to drive a moped or quad bike');
} else if (age >= 17) {
console.log('Allowed to drive a car');
} else {
console.log('Not allowed to drive');
}
Let's break this logic down:
- The first
if
condition checks if the person is aged exactly 16, in which case they are allowed to drive a moped or a quad bike on public roads. - The
else if
statement checks If they are aged 17 or over, meaning that they are allowed to drive a car. - The
else
statement catches any other age that is less than 16, where they are not allowed to drive.
In the example above the first condition is false
, but the second condition is true
(18
is greater than or equal to 17
), so 'Allowed to drive a car'
is logged to the console.
For any other age that does not match either of the first two conditional statements, the code moves into the else
block as before.
When writing conditional logic you can write as many else if
statements as needed - there is no limit. You can chain more conditions with the following syntax:
if (condition1) {
} else if (condition2) {
} else if (condition3) {
} else if (condition4) {
...
switch
if
/ else
statements are useful when you have several conditions to assess and a substantial amount of code to execute in each case.
However, if you have a larger number of conditions to check and a small amount of code to run for each option, a switch
statement is often a better alternative.
Basic syntax
To illustrate this, let's say we're creating a game. In this game we have a character that needs to perform a specific action based on a user's input.
First we'll declare the type of action as a variable, and the outline of a switch
statement:
let action = 'jump';
switch (action) {
}
As you can see, so far it's very similar to an if
statement. We use the switch
keyword and specify a condition in parentheses ()
(in this case the action
variable), followed by curly braces {}
for a code block.
case
Inside the curly braces {}
we can define one or more cases using the case
keyword:
let action = 'jump';
switch (action) {
case 'jump':
}
In this case
we're checking if the action
matches the string 'jump'
, followed by a colon :
. After the colon :
we can specify the code that needs to be executed:
let action = 'jump';
switch (action) {
case 'jump':
console.log('The character is jumping');
}
The switch
statement will evaluate the condition inside the parentheses ()
. If the action
matches the case
of 'jump'
, we simply log some text to the console.
break
After any executed code we always need to end the case
with the break
keyword:
let action = 'jump';
switch (action) {
case 'jump':
console.log('The character is jumping');
break;
}
The break
keyword ends the switch
statement logic, and ensures that no other code block runs once we've found a match. If we run this code, 'The character is jumping'
will be outputted to the terminal.
Multiple conditions
Now that you understand the syntax for a single case, let's add some more:
let action = 'run';
switch (action) {
case 'jump':
console.log('The character is jumping');
break;
case 'run':
console.log('The character is running');
break;
case 'fly':
console.log('The character is flying');
break;
}
If we change the value in the action
variable to run
and execute the code, we see that 'The character is running'
is logged instead.
default
At this point you may be wondering what happens if a user enters an unexpected value. For example, what if we change the action
to 'swim'
and run the code:
let action = 'swim';
switch (action) {
case 'jump':
console.log('The character is jumping');
break;
case 'run':
console.log('The character is running');
break;
case 'fly':
console.log('The character is flying');
break;
}
In this scenario, nothing is logged to the console because none of the cases match.
It's always a good practice to handle these edge cases, and the switch
statement offers the default
keyword to do just that:
let action = 'swim';
switch (action) {
case 'jump':
console.log('The character is jumping');
break;
case 'run':
console.log('The character is running');
break;
case 'fly':
console.log('The character is flying');
break;
default:
console.log('Invalid input');
}
Now if you run the code with the unrecognised string 'swim'
, you should see 'Invalid input'
outputted to the console.
As such, the default
keyword enables us to define a fallback if the incoming value does not match any of the cases that we have defined.
Summary
At this point you've learned everything you need to know about conditional logic in JavaScript in order to start writing basic applications.
We've covered what conditional statements are, as well as the different types, including if
, else
, else if
, and switch
.