Coding for Kids

Conditional Statements

In your programs, you will want the computer to make decisions based on what's happening. If a monster's hit points go down to zero, you defeated it so remove it from the game.

We make decisions all the time too. If the weather is cold, then put on a jacket, otherwise wear a t-shirt. That's a conditional.

When you break it down, every decision we make is based on whether something is true or false. You may have to think of it a little differently to see how that's possible. Do I need an umbrella? Well, you'd look outside to see: is it raining? If yes, that's true and if not, then it's false.

Booleans

For a conditional to work, you need to understand Booleans. Those are the true or false variables. Every conditional check needs to know what to do if the statement you ask about is true. Optionally, you can also tell the computer what to do if the conditional is false.

Comparisons and Logical Operators

You should make sure you've learned about comparisons and logical operators, like equality ===, greater than >, NOT !, and so on. Each of these comparisons returns a Boolean and that's what you need for the computer to make decisions.

Conditional Types

There are two main types of conditional statements.

The If/Else Statement

The if/else statement is the fundamental building block of decision-making in computers. You set up the statement to check for a certain condition. If that condition is true then you do something.

You also have the option of adding a secondary action if the condition was false.

As with many decisions, you may need to check for a few things, or check certain things only if other things happened, and so on. An if/else chain can become very complex, based on your needs.

Read about the if/else statement here.

The Switch Statement

The switch statement is a useful tool when you have a long list of items to check for. It's like a long if/else block. Using this cleans up the code a lot.

It works a little differently than the if/else statement, though. You don't make comparisons here, you set up cases.

Let's say you want to pick a movie to watch. For each movie, you have a certain type of snack you like to eat. You could set up a switch statement, where each case is the name (or type) of movie, and inside the code block for the case you assign the snack.

Read about the switch statement here.

If you're ready, then switch on over to the next page!

—Dr. Wolf