Control The Flow Of Your Code With If-Else And Switch Statements.

CONDITIONAL CONTROL STATEMENTS

ยท

7 min read

Control The Flow Of Your Code With If-Else And Switch Statements.

When you write a program, its primary goal is to solve a problem or many.

Suppose you are working on a website for some school. This website will be accessed by different users - students and teachers. You don't want students accessing their own database and becoming overnight toppers.

You need to control who gets to access what part of your code. The most basic requirement in such cases is the CONTROL STATEMENTS.

WHAT ARE CONTROL STATEMENTS?

These statements allow us to specify the order of the execution of our code while following the set of instructions provided. We can let the program decide what part of the code, and how many times it should execute depending on the situation.

There are two types of control statements- Conditional Control Statements and Looping Control Statements.

This blog will talk about conditional control statements.

LET'S DIG INTO CONDITIONAL CONTROL STATEMENTS!

Conditional Control Statements help us to execute the code based on a given condition. We can break the usual linear flow of our code and choose certain blocks of the code that will run depending on the condition.

There are two kinds of conditional control statements - The If-else statement and The switch statement.

THE IF - ELSE STATEMENT

These statements are divided into two blocks- if and else.

A condition is given to the if block and the else block is executed in the rest of the other cases except the one given in the if block.

if (condition) {
//The block of the code for the given condition.
} else {
//The block of the code for all the other conditions.
}

The above code shows the general way of writing an if - else statement. This structure is known as a control structure.

Here, the else statement is not necessary, you can always skip that part if you don't need it and the code will just jump to the next part ignoring the if statement if the condition is false.

What if you want to give more conditions rather than just one? No worries, just add an else if block and give another condition. There is no limit. You can add as many conditions as you want!

if (condition 1) {
//The block of the code for the given condition.
} else if (condition 2) {
//The block of the code for the given condition.
} else if (condition 3){
//The block of the code for the given condition.
} else {
//The block of the code for all the other conditions. (optional)
}

Let's look at an example where the if - else statement helps us to show an output based on the given conditions. The below code is written in JavaScript, but the control statements are common in all the coding languages.

let inTummy = `cookie`;

if (inTummy === `cookie`){
  console.log(`The monster ate the cookie. ๐Ÿช`);
} else if (inTummy === `chocolate`){
  console.log(`The monster ate the chocolate. ๐Ÿซ`);
} else if (inTummy === `candy`){
  console.log(`The monster ate the candy. ๐Ÿฌ`)
} else {
  console.log(`All the sweets were saved! ๐Ÿฅณ`);
}
//output
The monster ate the cookie. ๐Ÿช

In the above code, there were several blocks of code written, each with a different output but as a final output, only one got executed. That's because an if - else statement was used and we were able to control the output depending on the input.

Let's change the input from cookie to chocolate and see what happens!

inTummy = `chocolate`
//output
The monster ate the chocolate. ๐Ÿซ

The output changes as soon as we change the input, also without even writing a whole new block of code again!

How does the else block work? Well, if the input does not match any of the conditions given, the code written in the else block will be executed. If no else block is given then it will simply ignore the if block and continue normally.

inTummy = `hunger`
//output
All the sweets were saved. ๐Ÿฅณ

Fun Activity: Copy the above if-else statement and run it without the else block and notice the change. What happens to the output if the input is candy?

That's how the if-else statements work. Now let's look into how the switch statement works.

THE SWITCH STATEMENT

The switch statement is similar to the if - else statement but is focused on the equality operator only. We can technically use it for other operators too but that's not the purpose of the switch statement.

We use switch , case , break , and default in this statement.

The control structure is given below.

switch (variable to compare) {
  case /*compare to*/ :
    //block of code to be executed if equality is true.
    break;
  case /*compare to*/ :
    //block of code to be executed if equality is true.
    break;
  case /*compare to*/ :
    //block of code to be executed if equality is true.
    break;
  default: //block of code to be executed in the rest of the cases.
}

Let's break down the above code into smaller components to understand it.

  • The switch (variable to compare) will take the variable that you want to compare to different values.

  • The case is where you give the value you want to compare the variable to. It can be a string, number, variable, etc. In front of case assign the value followed by a colon :.

  • Under each case you can write the block of code you want to execute and then finish that block with a break;. Without the break;, the statement will continue to run all the blocks of code until it finds a break;.

  • The default: acts like else . The block of code given to the default: will get executed if none of the values matches the variable passed to the switch().

What if you want to have the same block of code for more than one case? It's simple. Just stack all cases below each other and then write the code for all of them!

  case /*value to compare*/:
  case /*value to compare*/:
    //block of code
  break;

The above block of code will run for both the cases !

Let's use the same example we used for the if - else statement and see how it would look in a switch statement.

let inTummy = `cookie`;

switch(inTummy) {
  case `cookie`:
    console.log(`The monster ate the cookie. ๐Ÿช`);
    break;
  case `chocolate`:
    console.log(`The monster ate the chocolate. ๐Ÿซ`);
    break;
  case `candy`:
    console.log(`The monster ate the candy. ๐Ÿฌ`);
    break;
default: 
  console.log(`All the sweets were saved. ๐Ÿฅณ`);
}
//output
The monster ate the cookie. ๐Ÿช

The above code has several blocks of code but only the one that equates to the variable given in the switch() executes. Let's assign chocolate to that variable and see what happens to the output.

inTummy = `chocolate`
//output
The monster ate the chocolate. ๐Ÿซ

Again, we just executed another piece of code just by changing the value of the variable.

As you might have noticed, this controlled structure is simply checking if the value assigned to case is equal to the one given to switch() . It does not check for any other conditions like "greater than" or "less than".

Fun Activity: Observe the code below. Do you find any mistakes? Can you remove some blocks of code without changing the way the program behaves? Can you write the same code using if - else statement?

const inTummy = `candy`

switch(inTummy){
  case `candy`:
    console.log(`The monster ate the candy. ๐Ÿฌ`);
  case `carrot`:
    console.log(`The monster does not like vegetables. ๐Ÿคข`);
  case`potato`:
    console.log(`The monster does not like vegetables. ๐Ÿคข`);
  default:
    console.log(`All the sweets and vegetables were saved. ๐Ÿฅณ`);
}

Don't forget to copy and run the above code and play with it in your own code editor!

CONCLUSION

Before we finish, let's talk about which one of the above two should be used and when.

Nowadays, the switch statement is not seen much in the industry. Also, it has a few more lines of code as compared to the if - else statement. But it does make the code look more readable.

The if - else statements can do what the switch statement does and is capable of much more. You can give more conditions in an if - else statement and it has fewer lines of code.

So it all comes down to your own preference. Although, in some cases, like the one used in the above example of sweets, the switch statement provides better readability. But it's up to you to decide what works best for you.

ย