Conditions

You are constantly using conditional statements in your everyday life. Is the water boiling in the pot? If it is, put in the pasta. Otherwise, wait a few more minutes. 🧑‍🍳

It’s the same in your code. Depending on the data, you can instruct your program or algorithm to act differently.

Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Click here to get in touch.

Let’s set things up for this lesson.

Make a new folder somewhere on your computer, open it with VS Code, and create two files:

  • main.ts, where we will write our code. To start, you can add console.log("Hello!"); to it.
  • deno.json, which lets VS Code know this is a Deno project and enables the Deno extension. You can tweak settings in this file, but we’ll keep it empty for now.

Open the terminal and run the following command: deno run --watch --check main.ts

This command clears the terminal and reruns main.ts every time you save it (CMD + S on Mac or CTRL + S on PC).

You can use this setup to test the code provided in this lesson.

A screenshot showing VS Code running and watching a TypeScript file.

Conditional statements

To write conditions, we use the conditional statements if, else if, and else.

The first condition should always be tested with if. The condition should be enclosed in (). If the condition is met, the computer will execute the code inside the following {}.

If we want to test more than one condition, we use else if with a condition in () followed by code to be executed inside {}. Testing multiple conditions isn’t always necessary.

If we want to run some code when none of the conditions are met, we use else. Since else doesn’t test any condition, we don’t need (), but we must provide the code to be executed inside {}. Although finishing with an else isn’t mandatory, it often helps prevent unexpected bugs.

For example, the code below compares myAge and yourAge:

  • If myAge is greater than yourAge (line 6), we log I am older than you! in the terminal. The remaining conditional statements are skipped.
  • If the first condition is not met, we check another condition with else if (line 8). If myAge is smaller than yourAge, we log You are older than me!. The remaining conditional statements are skipped.
  • Finally, if none of the conditions above are met, it means that we are the same age. In this case, we use else (line 10) to log We are the same age!.
main.ts
// Change the ages
// to test the different outcomes.
const myAge = 36;
const yourAge = 25;
 
if (myAge > yourAge) {
  console.log("I am older than you!");
} else if (myAge < yourAge) {
  console.log("You are older than me!");
} else {
  console.log("We are the same age!");
}

A screenshot showing VS Code running a TypeScript file with if, else if, and else statements.

💡

Have you noticed the absence of ; on line 12? It’s because when you use {}, you create a block of code. The closing curly bracket already tells the computer that it’s the end of the block, so there’s no need for an extra semicolon at the end.

Comparison operators

When using if and else if, the condition inside the () should always result in a boolean value (true or false).

The previous example works because we used the comparison operators > and <, which return a boolean.

Here are the main comparison operators you’ll use in your daily work:

  • >: greater than
  • >=: greater than or equal to
  • <: less than
  • <=: less than or equal to
  • ===: equal to
  • !==: not equal to
💡

You might see examples around the web with == and !=. These operators don’t check for the type of values, so it’s best to stick with === and !==, which check for strict equality.

And here are the operators in action. We store the results in variables and log them:

main.ts
// Change the ages to test the different operators.
// Don't worry about the `: number` for now.
const myAge: number = 36;
const yourAge: number = 25;
 
const greater = myAge > yourAge;
console.log("greater =>", greater);
 
const greaterOrEqual = myAge >= yourAge;
console.log("greaterOrEqual =>", greaterOrEqual);
 
const younger = myAge < yourAge;
console.log("younger =>", younger);
 
const youngerOrEqual = myAge <= yourAge;
console.log("youngerOrEqual =>", youngerOrEqual);
 
const sameAge = myAge === yourAge;
console.log("sameAge =>", sameAge);
 
const differentAge = myAge !== yourAge;
console.log("differentAge =>", differentAge);

A screenshot showing VS Code running a TypeScript file with comparison operators.

Logical operators

Sometimes, you want to check multiple conditions in one statement. This is where logical operators && and || are useful.

  • && means AND
  • || means OR

For example, let’s say we need an algorithm to check if you are old enough to have a drink in a bar in Quebec (at least 18) or Ontario (at least 19). In case you don’t know, Quebec and Ontario are Canadian provinces. 🥂🇨🇦

Without logical operators, it could look like this, with nested conditions. It works, but nested conditions can be difficult to read and debug.

main.ts
// Change the age and province to test the conditions.
// Don't worry about the `: number` and `: string` for now.
const myAge: number = 18;
const myProvince: string = "Quebec";
 
if (myProvince === "Quebec") {
  if (myAge >= 18) {
    console.log("You are allowed!");
  } else {
    console.log("You are not allowed!");
  }
} else if (myProvince === "Ontario") {
  if (myAge >= 19) {
    console.log("You are allowed!");
  } else {
    console.log("You are not allowed!");
  }
} else {
  console.log("I don't know this province!");
}

Here’s the same code with the logical operator && to make sure age AND province meet specific conditions. This approach is simpler to understand and easier to debug!

Here’s what the code below does:

  • On line 6, we check if myProvince is "Quebec" AND myAge is greater than or equal to 18. If this is true, you can order a drink.
  • On line 8, we check if myProvince is "Ontario" AND myAge is greater than or equal to 19. If this is true, you can order a drink.
  • By this point, it’s possible the province is something unexpected. On line 10, we check if myProvince is not "Quebec" AND not "Ontario". If this is true, we let the user know we don’t recognize this province.
  • On line 12, the only remaining possibility is that the user is not allowed to order a drink.
main.ts
// Change the age and province to test the conditions.
// Don't worry about the `: number` and `: string` for now.
const myAge: number = 18;
const myProvince: string = "Quebec";
 
if (myProvince === "Quebec" && myAge >= 18) {
  console.log("You are allowed!");
} else if (myProvince === "Ontario" && myAge >= 19) {
  console.log("You are allowed!");
} else if (myProvince !== "Quebec" && myProvince !== "Ontario") {
  console.log("I don't know this province!");
} else {
  console.log("You are not allowed!");
}

We could also write the same algorithm with a mix of && and ||. Additionally, we can use variables to simplify the code.

Here’s what the code below does:

  • On line 6, we check if myProvince is "Quebec" AND myAge is greater than or equal to 18. We store the result in the variable isAllowedInQuebec, which can only be true or false. (If you hover over it, you’ll see its type is boolean.)
  • On line 7, we do the same for Ontario, storing the result in isAllowedInOntario.
  • On line 9, we check if isAllowedInQuebec is true OR isAllowedInOntario is true. Only one of these needs to be true for the code inside the following {} to execute.
  • On line 11, we log a message to the user if the province is something unexpected.
  • By the time the computer reaches line 13, the only remaining possibility is that the user is not allowed to order a drink!
main.ts
// Change the age and province to test the conditions.
// Don't worry about the `: number` and `: string` for now.
const myAge: number = 18;
const myProvince: string = "Quebec";
 
const isAllowedInQuebec = myProvince === "Quebec" && myAge >= 18;
const isAllowedInOntario = myProvince === "Ontario" && myAge >= 19;
 
if (isAllowedInQuebec || isAllowedInOntario) {
  console.log("You are allowed!");
} else if (myProvince !== "Quebec" && myProvince !== "Ontario") {
  console.log("I don't know this province!");
} else {
  console.log("You are not allowed!");
}

Conditional operator

There’s another way to write simple conditional statements using the condition ? if true : if false syntax. This syntax is called the conditional operator (also known as the ternary operator).

It’s great for simple conditions, allowing you to replace if and else statements with a single line.

Here’s another variation of our algorithm using this syntax. One other notable difference is that instead of using console.log multiple times, we create a variable message and log it just once at the end.

Here’s what the code does:

  • On line 6, we create a variable message with an empty string. We use let so we can overwrite its value later.
  • On line 8, we check if myProvince is equal to "Quebec". If the province is Quebec, line 9 gets executed:
    • If myAge is greater than or equal to 18, message is overwritten with "You are allowed!".
    • Otherwise, message is overwritten with "You are not allowed!".
  • On line 10, we check if myProvince is equal to "Ontario". If the province is Ontario, line 11 gets executed:
    • If myAge is greater than or equal to 19, message is overwritten with "You are allowed!".
    • Otherwise, message is overwritten with "You are not allowed!".
  • By line 12, the only possibility left is that the province is not Quebec or Ontario. So we overwrite the message on line 13 with "I don't know this province!".
  • On line 16, we log the updated message.
main.ts
// Change the age and province to test the conditions.
// Don't worry about the `: number` and `: string` for now.
const myAge: number = 18;
const myProvince: string = "Quebec";
 
let message = "";
 
if (myProvince === "Quebec") {
  message = myAge >= 18 ? "You are allowed!" : "You are not allowed!";
} else if (myProvince === "Ontario") {
  message = myAge >= 19 ? "You are allowed!" : "You are not allowed!";
} else {
  message = "I don't know this province!";
}
 
console.log(message);

Conclusion

All of the algorithms discussed above for checking if the user can order a drink will produce the same results. But which one is THE BEST?

Well, it really depends on the context and your personal preferences.

Remember, you are learning a programming language. And just like in any language, there are many ways to express the same idea. As long as your computer and colleagues can understand you, you’ll be fine! 🤖

Now, it’s time for the next lesson. Let’s discover loops!

Enjoyed this? Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Get in touch if you have any questions.