TypeScript if, else & switch Conditional Control Tutorial
In this TypeScript tutorial we learn to control the flow of our application through the if, else if, else and switch statements.
We also learn how to nest conditional statements inside one another, and use the shorthand method of writing an if statement with the ternary operator.
What is conditional control
We can control the flow of our application by evaluating certain conditions. Based on the result of the evaluation, we can then execute certain sections of code.
As an example, let’s consider an application with a member area. To gain access to the member area, a user must provide the correct login credentials.
If the user provides the correct credentials, they are allowed to enter the member area. If not, they are given the option to try again or reset their password.
In pseudocode, the example above would look something like this.
if username == db_username && password == db_password
redirect to member area
otherwise
if forgot_password
reset password
otherwise
try_again
The actual code will not look like the example above, but it serves to give you an example of what conditional control is used for.
We can use conditional control in TypeScript through the following statements, in combination with comparison and logical operators.
- if
- else if
- else
- switch
The if statement
The if statement will evaluate if a condition is true or not.
If a condition proves true, the compiler will execute the code in the if statement’s code block. If the condition proves false, the compiler will move on to the next statement outside and below the code block.
An if statement is written with the keyword if , followed by the condition(s) we want to evaluate between parentheses.
Then, we specify a code block with open and close curly braces that will be executed if the condition proves true.
if (condition) {
// code to execute
// if condition is
// true
}
let num1 : number = 5
let num2 : number = 5
if (num1 == num2) {
console.log(num1, " is equal to ", num2)
}
In the example above, the if statement compares the two numbers to see if they are the same. Because they are, the message is printed to the console.
If we change one of the numbers to another value, the condition will be false and the message will not be printed.
let num1 : number = 5
let num2 : number = 3
if (num1 == num2) {
console.log(num1, " is equal to ", num2)
}
When we run the example above, nothing is printed to the console because the condition is false and the print statement never gets executed.
The else if ladder
The else if ladder can be used when we want to evaluate extra conditions that relate to our if statement.
To create an else if ladder, we simply add the keyword else between two if statements, connecting them.
if (condition1) {
// first condition
// to be evaluated
}
else if (condition2) {
// second condition
// to be evaluated
}
If the first condition proves false, the compiler will evaluate the second before moving on to any other code.
let num1 : number = 5
let num2 : number = 3
if (num1 < num2) {
console.log("if statement is true")
} else if (num1 > num2) {
console.log("else if statement is true")
}
We use else if ladders to connect our if statements together, sort of grouping them.
note An else if statement can only follow an if statement, it cannot stand on its own. The first conditional statement must always be an if.
The else fallback
The else statement acts as a catch-all fallback for anything that isn’t covered by an if statement or an else if ladder.
The else statement doesn’t need a conditional block in the header because it works as a catch-all. We only write the keyword else , followed by its execution block.
if (condition) {
// code to execute
// if condition is
// true
}
else {
// if above conditions
// are false, execute
// this block
}
note Like with the else if ladder, the else statement cannot stand on its own. It must follow an if statement or an else if ladder.
let num1 : number = 5
let num2 : number = 5
if (num1 < num2) {
console.log("if statement is true")
} else if (num1 > num2) {
console.log("else if statement is true")
} else {
console.log("none of the above is true, execute the else statement")
}
In the example above, our else execution block is executed because both if statements prove false.
Nesting if statements
TypeScript allows us to nest if statements inside other if statements. The compiler will evaluate each if statement in a hierarchical fashion.
All we do is write an if statement inside the execution block of another if statement.
let num1 : number = 10
if (num1 < 20) {
console.log("outer if execution")
if (num1 >= 10) {
console.log("inner if execution")
}
}
We’re not limited to one nested if statement. We can have as many nested if conditions as we need in one control structure set.
note We recommend not nesting more than three levels deep. Nesting too deep is a bad practice, in most situations we can use an alternative method.
The ternary operator ( ? : )
When we have an if else statement with only single execution statements, we can use what’s known as the ternary operator as a shorthand method to write it.
To use the ternary operator, we write the condition between parentheses first, followed by a ? (question mark) operator.
Then, we write the single execution statement if the condition proves true, followed by the : (colon) operator.
Finally, we write the single execution statement if the condition proves false, and terminate the whole expression with a semicolon.
(condition) ? if_true_statement : if_false_statement
Let’s consider the following if else statement.
let num : number = 8
if (num == 10) {
console.log("num == 10")
} else {
console.log("num != 10")
}
In the example above, we evaluate if a number is 10 or not, and print a message to the console. Let’s convert this into shorthand with the ternary operator.
let num : number = 8
// condition if true statement if false statement
(num == 10) ? console.log("num == 10") : console.log("num != 10")
It may seem confusing at first, especially if you’ve only been writing traditional if statements for a while, but with practice it becomes second nature.
note It’s important to note that many developers do not like to use the ternary operator because it makes the code harder to read, especially for new developers.
It can also result in some impenetrably complex expressions. Some employers even disallow its use altogether.
For this reason, we’ll only be using traditional if else statements throughout this tutorial course, but feel free to practice the ternary in case you come across it in the wild.
The switch statement
We use the switch statement when we want to compare a single value against a list of many other values.
Before we explain how it works, let’s look at the syntax first.
switch (main_value) {
case check_against_value1 :
// if true execute this code
break;
case check_against_value2 :
// if true execute this code
break;
default:
// if none of the cases are true
}
First, we specify the main value that we will be comparing other values against. Then, in the code block, we specify our cases.
A case consists of the value we want to compare against the main value, and execution code after the : (colon) if the comparison proves true.
The break keyword tells the compiler that we’ve found what we’re looking for in the switch, so it can break out of it and continue on to code outside and below the switch.
The default case acts as our fallback statement, much like an else statement. In fact, the switch statement above is comparable to the following if statement.
if (main_value == check_against_value1) {
// if true execute this code
} else if (main_value == check_against_value2) {
// if true execute this code
} else {
// if none of the cases are true
}
Let’s see a real world example.
let grade : string = 'B'
switch (grade) {
case 'A':
console.log("You got an A. Excellent!")
break;
case 'B':
console.log("You got a B. Good Job.")
break;
case 'C':
console.log("You got a C. Well done.")
break;
case 'D':
console.log("You got a D. You passed.")
break;
case 'F':
console.log("You got an F. Sorry, you failed.")
break;
default:
console.log("Unknown grade, please see the teacher.")
}
In the example above, we have a single main value (grade) that’s being evaluated against multiple cases. When a case evaluates to true, the execution statement after the colon executes.
note Typically a switch statement is only used when we want to compare one value to many others.
Summary: Points to remember
- We control the flow of our application with if , else if , else and switch conditional control statements.
- The else if ladder and else statement cannot stand on their own, they must be part of an if statement.
- The else statement represents everything that the if and else if statements do not cover.
- We can nest conditionals by writing them inside the execution blocks of other conditionals.
- The ternary operator is a shorthand method of writing an if else statement with only a single execution statement.
- A switch statement is used to compare one value against many.