Coding for Kids

Variable Type: Boolean

A Boolean value can only be true or false. It can't be anything else.

These are useful flags for programs and they're used more than you'd think. Whenever we run a statement with a conditional (such as if, while, for) a comparison is made. If true, one thing happens. If false, a different thing might happen. We can set a Boolean in a number of ways.

Declare a Boolean

As with all variables, you start with the keyword let. You then set it equal to true or set it equal to false. Don't use any quote marks or other punctuation. You can also set a variable equal to some expression that gets interpreted as true, such as (3 < 5), or false, such as (3 > 5).

Syntax

Examples:

See if you can make sense of these examples. The first just sets the value as true. The second and third do a numerical comparison using greater than and less than, just like in math. The third one tests to see if the first number (5) is strictly equal to === the second number (6). Well, they're not the same, so it's false. The last one calls a function to process something. The function has to return a Boolean value based on whatever it's doing.

The NOT ! operator:

A Boolean variable is like an on/off switch. You can easily flip its value. All we need to do is use the NOT operator: !. Put this exclamation point in front of the Boolean and you change its interpretation (but not its actual value).

Using examples from above:

By the way, if you wanted to make a toggle flag, this is an easy way to do it, using the NOT operator (!).

A toggle is something that flips back and forth from on to off to on, etc., or true to false, and so on. Think of it like clicking a pen; now you can use it, now you can't, now you can...

myToggle = !myToggle;

In this case, whatever your toggle value is, it gets flipped. This only works for true and false. Let's say you have two players in a game. One way to control whose turn it is could be through using a toggle. If it's not player 1's turn, then it must be player 2's turn. And when player 2's turn is up, it flips back to player 1.

Always be true to yourself!

—Dr. Wolf