Coding for Kids

Conditionals: Nested if/else Statement

With a single if block, you just test if something is true and react to that. When you pair up an ifstatement with an else statement, you don't just do something if the condition is true, you also do something if the condition is false.

What if you have a bunch of conditions to test for? This is where we get into nested blocks.

There are two versions of nesting these statements. Let's tackle the straightforward one first.

Simple Nested Conditional Block

This acts sort of like a checklist. You go down the list of checks until you get to something that is true and then you stop checking. That's the important part. Once you find something true, you exit the block.

You always go down from top to bottom, like all statements in your code blocks.

Syntax:

You can put as many checks as you need. This actually tests for four situations. The first three are stated specifically, and then the last else block serves as a catch-all for everything that wasn't caught before.

You don't need to use a catch-all like that. You can leave off the last else block if that makes sense for what you need your program to do.

Example:

Let's stick with our weather example. How about this: If it is snowing, then wear gloves. If it's not snowing, but it's raining, then get your umbrella. If it's neither snowing nor raining, then take your sunglasses.

It sounds like a lot, but the if/else structure will show the way! Let's turn this into code.

  • if (itIsSnowing)
  • {
    • putOnGloves(); //this happens if it's snowing
  • }
  • else if (itIsRaining) //if not snowing, check this
  • {
    • getUmbrella(); //do this if it is raining
  • }
  • else //or if it's not snowing and not raining
  • {
    • getSunglasses(); //do this
  • }
Coding for Kids

Take it one step at a time. In the first if statement, we check to see if it is snowing. If so, we run the first code block. But then we exit the rest of the conditional statements because the code block ends after putting on gloves.

Remember that else only runs when the if statement is false. So, if it is snowing, then we never even check for rain. In this example, you wouldn't bring your umbrella out in the snow, even if there was rain mixed in with the snow.

By combining else and if in the second statement to check for rain, we lock these conditionals together. This is called nesting. One conditional is nested inside another. It doesn't run on its own unless the first conditional needs it to.

Notice that the final else doesn't have an if attached to it? It could if that's what you needed. In this case, it's a catch-all. Whatever makes it through the first two checks gets caught here and this code runs. But what if it's nighttime? Would you need your sunglasses? No probably not. We could change this block if we wanted to. Let's consider this slight change.

Example 2:

  • if (itIsSnowing)
  • {
    • putOnGloves(); //this happens if it's snowing
  • }
  • else if (itIsRaining) //if not snowing, check this
  • {
    • getUmbrella(); //do this if it is raining
  • }
  • else if (itIsSunny) //or if it's not snowing and not raining, then check for sun
  • {
    • getSunglasses(); //do this
  • }
Coding for Kids

Here's what happens:

  1. We check if it is snowing.
    1. If yes, then we put on gloves and go (we don't even check about the umbrella or sunglasses).
    2. If it's not snowing then we keep checking for more.
  2. We check if it is raining.
    1. If yes, then we get the umbrella and we're on our way (we don't look for sunshine).
    2. If it's not raining, then we keep checking for more.
  3. We check if it is sunny.
    1. If so, then we get our sunglasses. And that's it.
    2. There's nothing else here. If there is any other weather condition then we don't do anything for it here. It doesn't matter if it's day or night, hailing, or if meteors are falling. Nothing else happens.

This may sound like we're not being careful or complete, but there are lots of times where want something to happen only if certain things are true and not when they're false. Think about maintenance in a car. You only need to get gas or check oil when there's a problem. You don’t need to do anything the rest of the time.

Be careful when nesting statements

You have to be very careful when you're nesting if statements together. You have to remember that the code reads from top to bottom. If the first condition is true then the rest of the code never gets looked at. I'm going to give you an example that does not work. I'm going to stick it in a function so we can keep calling it with different values. As always, you should type this in too and play with it on your own. See if you get the same thing. Change things up and try again. You know... practice and learn.

Example 1:

Here's the bad function we're going to use.

  • function reportTestPerformance(score)
  • {
    • if (score >= 65)
    • {
      • alert("You passed.");
    • }
    • else if (score > 80)
    • {
      • alert("You did well.");
    • }
    • else if (score > 90)
    • {
      • alert("Excellent job!");
    • }
    • else if (score === 100)
    • {
      • alert("Perfect score!");
    • }
    • else
    • {
      • alert("You failed.");
    • }
  • }
Coding for Kids

Run some test cases.

What's going on? We had all those possibilities but none are working unless we fail. Don't worry, this happens all the time. You have to be careful of the order. If you look at the first condition, we are checking to see if a score is 65 or higher. The first three cases we sent in are 65 or higher, so that code block gets triggered. It runs and it escapes and the other score checks never happen.

What you don't see is that the failing score (the 57) gets passed along to all the other checks before getting dumped into the catch-all else statement at the end.

How do we fix this? We have to change the order of the scores we're checking it. How you arrange them depends on what you're testing for. If these were in golf, we'd want lower numbers for better praise. For a test, we want higher numbers. Let's fix this function and run those test cases again.

Example 2:

Here's the improved function that acts the way we want it to.

  • function reportTestPerformance(score)
  • {
    • if (score === 100)
    • {
      • alert("Perfect score!");
    • }
    • else if (score > 90)
    • {
      • alert("Excellent job!");
    • }
    • else if (score > 80)
    • {
      • alert("You did well.");
    • }
    • else if (score >= 65)
    • {
      • alert("You passed.");
    • }
    • else
    • {
      • alert("You failed.");
    • }
  • }
Coding for Kids

Here are the same test cases.

There it is, working perfectly! Oh, but you may be asking yourself about that 90. Why did it come up as "You did well." and not as "Excellent job!"? Can you examine the code and see why? It's actually working the way it should based on how we wrote it.

Yeah, it's because we have score > 90, not score >= 90 (with the equals sign). Since 90 is not greater than 90, our current score check is considered false. You can fix it if you like.

The point is that you have to be careful about your conditionals and make sure you're testing your code in many ways to get the results you're expecting.

Last thing here... What would have happened if we got rid of the else keyword before all the ifs? Think about it.

Without the else statements in there, each conditional would be a separate check, not nested together. You wouldn't exit out once one part is true. Passing in a score of 100 would get you four different popups! You would see all of them except the failing one. In this case, that's not what we want. But you may have a case where that is what you want. That's the funny thing about code. Each situation is different.

Compound Nesting

This gets a little more challenging. For this, we will put if/else code blocks inside other if/else code blocks to create a deep "thought process" for making decisions.

There will be a lot of open and closing braces to pay attention to. Whitespace indenting becomes important for keeping track of where you are in the code.

Example:

Let's talk about the weather again. We won't get super-complicated here but let's consider this...

If it is precipitating (raining or snowing) then we want to accessorize for that. If there's some other kind of precipitation (like cats and dogs literally dropping from the sky) then we'lll take shelter somewhere until the storm passes.

If it's not precipitating, then we want to wear a hat if we have one. If not, let's not do anything.

So we can test this out, we're going to have the computer randomly assign true or false to our variables. The method Math.random() returns a decimal from 0 up to 1. If we call the function and check if it's less than halfway between 0 and 1, we should get true half the time and false the rest of the time. We'll also print those variables to the console so we can see them. This will let us test everything out.

This won't be a perfect test because randomly, it may snow but it could also say there's no precipitation. But that's not the point of this exercise so let's not worry about that part.

Got the situation? Let's code it!

  • //each of these has a 50% chance of being true
  • let precipitation = Math.random() < 0.5;
  • let snow = Math.random() < 0.5;
  • let rain = Math.random() < 0.5;
  • let hat = Math.random() < 0.5;
  •  
  • //print the variables to the console
  • console.log("********************");
  • console.log("precipitation: " + precipitation);
  • console.log("snow: " + snow);
  • console.log("rain: " + rain);
  • console.log("hat: " + hat);
  • console.log("********************");
  •  
  • //let's begin the conditional blocks
  • if (precipitation)
  • {
    • console.log("It's precipitating...");
    • if (snow)
    • {
      • console.log("There's snow! Put on a heavy coat!");
    • }
    • else if (rain)
    • {
      • console.log("Grab your umbrella!");
    • }
    • else
    • {
      • console.log("Run for shelter!");
    • }
  • else if (hat)
  • {
    • console.log("A good hat will block out the sun!");
  • }
Coding for Kids

Run it a bunch of times and see what happens. Check the console window for all the results.

You should see that if the precipitation variable is false, then it never comments on snow or rain. Sometimes it mentions your hat and sometimes it doesn't say anything at all.

If there is precipitation then it may comment on the snow or the rain or it will tell you to take shelter.

You able to work all that out? So you see how the blocks are inside of other blocks? And do see how indenting carefully can make it easier to read the code? Easier to see which blocks are inside other blocks?

Challenge yourself to make this even more detailed and test it out!

Do your best when you test your nest!

—Dr. Wolf