What are if else statements in programming? How do I use them? Why should I care?

Today it’s time for the third part of this Flutter course. What we will take a look at today are ‘if’ and ‘else’ statements. I believe these are one of the easier concepts to grasp in programming because they are so similar to our natural speaking language. I will do my best to make them an easy concept to grasp.

What are if else statements?

So firstly lets start by explaining what they are. An if else statement is a way of checking something in your code. If we want to know whether a number is equal to 10 we can use an if else statement. In natural language it would sound like this; if this number is equal to 10 then do something, otherwise (else) do something else. In code this statement looks like this;

if (thisNumber == 10) {
     // do something
   } else {
     // do something else
   }

If you try to just read all of that out then I think you will hear that it sounds pretty similar to our sentence above. Let’s explain it. It consists of five parts:

If statement:

 if (thisNumber == 10)


Boolean expression:

thisNumber == 10


Operator:

==


else statement (which is not needed, but is sometimes useful):

else

If statement:

So essentially an if statement is like a clause. Meaning that the stuff inside the scope (inside the curly braces ‘{}’) of an if statement does not get called or does not get executed (executed would be more correct term) unless the if statement evaluates to true. Evaluates to true means that if what is inside the if statement (inside the parenthesis ‘()’) is true, then what is within the curly braces gets executed. Inside the parenthesis we have what is called a boolean expression. If we remember from part one (what are variables in programming) then we know that there is a variable called bool which can be either true or false.

Boolean expression:

A boolean expression then, is a statement that will either evaluate to true or to false. Our if statement could just as well look like this;

bool jonSnowKnowsNothing = true;

if (jonSnowKnowsNothing) {
    print("You know nothing Jon Snow");
  }

What do you think would happen if we run this piece of code? Also print(); is a statement that prints to the console/terminal whatever is within the parenthesis. So if we run this piece of code we would see something like

You know nothing Jon Snow

So our program prints; You know nothing Jon Snow. It does this because the if statement evaluates to true. The if statement evaluates to true because we set the variable inside the parentheisis to be equal to true

bool jonSnowKnowsNothing = true;

if we instead set it to be equal to false then our program will not print anything because we never get into our if statements scope. So really this is just to show that our if statement checks whether the sum of what is inside it is true. We could check whether several things are true or not inside our if statement. Which sounds like this; if Jon Snow knows nothing AND the earth is flat then print this is a true statement. And in code would look like this

bool jonSnowKnowsNothing = true; 
bool theEarthIsFlat = true;

if (jonSnowKnowsNothing && theEarthIsFlat) {
     print("This is a true statement");
   }

Our program would now print; This is a true statement. Because of course the earth is flat. Okay, but on a serious note if we have a statement that is true and one that is false then the entire statement is not true. So if we take a second look at our example above as it should be. The earth is not flat as far as I know so if we set that to be false instead. Then what happens?

bool jonSnowKnowsNothing = true; 
bool theEarthIsFlat = false;

if (jonSnowKnowsNothing && theEarthIsFlat) {
     print("This would be a crazy world");
   }

If the first statement is true and the second statement is true then we print; This would be a crazy world. But if either of the statements evaluates to false then both of them are not true which means we are locked out of our if statements scope.

Operators:

Let’s go through our boolean expression operators. An operator is the ‘&&’ that you saw above.

jonSnowKnowsNothing && theEarthIsFlat

We have also seen the equals operator ‘==’

thisNumber == 10

Comparison operators:
So what are they and what do they mean? We have seen the equals operator ‘==’ which just checks if a is equal to b. For this to work a and b have to be of the same type. You can’t compare an int to a String.

int a = 1;
int b = 2;

a == b

// this is false, 1 is not equal to 2

And here we have the second comparison operator. Not equal to; !=

int a = 1;
int b = 2;

a != b

// this is now true, because 1 is not equal to 2

If this is hard to grasp I suggest reading it as “it is true that 1 does not equal 2”. And then you will more easily see whether the expression is true or not. For instance if a = 1 and b = 1. And you read “is it true that 1 does not equal 1”. It may be easier to hear that that does not sound right.

We also have our greater than and less than operators; > <.

int a = 1;
int b = 2;

a > b

// this is false, because 1 is not greater than 2

A lot of people struggle with these operators at the start. And I have heard tons of explantations to try to make it easier. I will give you my advice for how to think. But with the caveat that the more you code and use them the easier it will get. And then you won’t have to even think. However, my advice would be to simply look at it as what side of the symbol is biggest?

>

The left side is bigger > the right side is smaller. I feel like this is the easiest way to remember since it is also what the operator does. It checks what is biggest. Think of it as an equals sign that has collapsed on one side. On the equals sign = the space between both lines are equal. But if this sign collapses on one side then there’s a huge gap on one of the sides > and no gap on the other.

Now we can combine these signs in different ways.

int a = 1;
int b = 2;

a == b // one is equal to two? false
a > b // one is greater than two? false
a < b // one is less than two? true   a != b // one is not equal to two? true   
a !> b // one is not greater than two? true
a !< b // one is not less than two? false

These are what are referred to as the comparison operators because we compare something. In this case we compare a with b.

Logical operators:
We also have a second category which is where ‘&&’ exists. These operators are referred to as logical operators. These are our AND, OR and NOT. Which look like this;

&& // AND
|| // OR
! // NOT

We have already seen ‘&&’ and ‘!’. Our NOT (!) operator can be difficult to grasp when explained. But I feel it’s easier to grasp when shown as I did above.

a != b // one is not equal to two? true
a !> b // one is not greater than two? true
a !< b // one is not less than two? false

As you may or may not see. All that our NOT operator does is it adds a ‘not’ into our sentences. If we remove the ‘!’ operator from the statement. Then we simply remove it from our sentence as well and we are back to normal.

// With NOT operator:
   a != b // one is not equal to two? true
   a !> b // one is not greater than two? true
   a !< b // one is not less than two? false

// Without NOT operator:
   a == b // one is equal to two? false
   a > b // one is greater than two? false
   a < b // one is less than two? true

Alright so that is what our NOT operator does. Now let’s move on to our OR and AND operators. These are logical, meaning that they do not work as our previous operators which compare things. Logical operators help combine multiple boolean expressions to create a single boolean output. That may have sounded like gibberish. Don’t worry, I will explain. Consider the parenthesis of our if statement, we check if what is inside here is true. That is called evaluating a boolean expression. We evaluate if it’s true.

if (thisNumber == 10)

AND operator:
Now we may want to check several things. Let’s say that we want to create a program that turns on our alarm when we leave the house. We only want the alarm to turn on if no one is inside the house. Otherwise it would go off, and that would be annoying. We are two people that live inside this house. So we only want the alarm to turn on if both Jon and Khalesi are out of the house. So essentially we want to check two things in our if statement. We want to se if Jon is out. And we want to se if Khalesi is out. Our logical AND operator helps us do this.

if (jonIsOut && khalesiIsOut) {
     print("Alarm truned on");
   }

This statement now checks whether the first part evaluates to true. Is jonIsOut true or false? Let’s say that he is out. Then it checks if khalesiIsOut is true or false? Let’s say that she is still home.

bool jonIsOut = true;
bool khalesiIsOut = false;

if (jonIsOut && khalesiIsOut) {
     print("Alarm truned on");
   }

Since both are not out, the entire expression evaluates to false. And so the alarm is not turned on. For our AND operator, both things on each side of the operator must evaluate to true.

Or operator ||:
New example. Let’s say that we want to build an app that reminds us to get milk. We want to be reminded either if our milk carton is completely empty or if our milk carton has less than 300 ml of milk left. Because 300 ml is what we know we drink every morning.

double milkLeft = 250.0;

if (milkLeft == 0 || milkLeft < 300) {
     orderMoreMilk();
   }

So this statement now takes care of exactly that for us. It checks whether the milk carton is empty (milkLeft == 0) or if the milk carton contains less than 300 ml of milk (milkLeft < 300). In our case the first part milkLeft == 0 is not true since milkLeft = 250. So that evaluates to false. The second part milkLeft < 300 is true since milkLeft = 250, which is less than 300. So if either one is true then the statement is true. Since one of the parts in our statement is true. The entire statement is true. So we get into the body of our if statement.

Else statement:

Now an else statement is not necessary. You can just have an if statement. You can also just have several if statements in a row

if (someInput == 2) {

}
if (someInput == 4) {

}

In this case we will check the variable ‘someInput’ twice. So we will get into both if statements if someInput is first equal to 2 and then equal to 4. Which could happen like this

int someInput = 2;

if (someInput == 2) {
     someInput = 4;
} 
if (someInput == 4) {

}

First someInput is equal to 2. So we get into the first if statement. Then inside the first if statement we set someInput to be equal to 4 instead. This means that when our program gets to our next if statement our variable someInput will be equal to 4. So we get into our second if statement.

This is rarely something that we use. What is more common is an ‘else if’ statement:

int someInput = 2;

if (someInput == 2) {
     someInput = 4;
} else if (someInput == 4) {

}

In this case our program checks both if statements and only lets us in to the one that is true from the start. Essentially seeing, is someInput equal to 2? Then, is someInput equal to 4? Depending on the answer we only get into the one that is true. The other one does not get checked again. This can be used if we have multiple cases we want to check for.

Example:

Let’s say that we want to create a game. And we want to create a specific method that is called when a person wins. The game has different levels in it. Depending on what level you are you get a specific bonus when you win. If you are level 1 you get a bag of cash. If you are level two you get a new custom theme. If you are level three (the highest level in this short as game) you get a Dank Meme. This could look like this

void gameWon(int level) {

  if (level == 1) {
    print("Here's your bag of cash");

  } else if (level == 2) {
    print("You get a new custom theme!");

  } else if (level == 3) {
    print("Congrats, you've won the game. Here is your DANK Meme");
    showMeme();

  } else {
    // this would be an error most likely. We would
    // only get here if the player has a level that is
    // greater than 3 or 0. Which should not happen.
    // Since we only have three levels in our game. 
    // A lonely 'else' statement is something that runs
    // if the other if statements are false. Kind of
    // like a safety net.
  }
}

Take a look at the code. What I would suggest is just thinking a bit about how you could implement a fifth level.

Conclusion:

Alright so that is what if statements are. Next part will be explaining what data structures are in programming. What I would suggest now though is that you take a look at a video I made about what classes are in Python. I think that at this point you will be able to get a lot out of that video. Python is a little bit different in terms of how things are written. But the principles are the same. So I would definitely recommend that you watch that video. I’m not necessarily promoting it, you can of course watch any other video if you want. Anywho, hope you learnt something from this one. Please give me feedback in the comments on things I could improve or if there was anything that you didn’t understand. And I will try to fix that for the next one!

2 Comments

  1. Avatar
    Steven Pompilio Sanchez Estanislado
    November 9, 2019

    Muy bien explicado Kalle, muy eficiente tu forma de enseñar sigue así y te agradezco el tiempo que le dedicas a este material de muy buena calidad, saludos desde México!.

    Reply
  2. Avatar
    OhenebaAduhene
    November 11, 2019

    Is a very great tutorial indeed, you’re really broading my understanding as a junior software engineer.
    But I want to ask, if you we to implement the codes in your tutorial and play around it, should we save it as a dart file.
    Thank you.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Join Clean Code Friday