Booleans

The simplest data type!

Named after this guy

George Boole, mid 19th century English mathematician and logician

Only two values

true & false

Can also think of them as

yes & no

on & off

etc.

Used with if

if (<boolean>) {
  // do something
}

Yeah, we haven’t learned about if yet.

… and with while

while (<boolean>) {
   // do something
}

Haven’t learned about while yet, either.

We’ll get to it.

But the key thing is

They are just another kind of value to compute with.

Literal booleans

As with numbers, we can write boolean values directly in our programs as follows.

true

false

That’s it.

Unlike numbers, there aren’t different ways of writing the same literal value.

What can we do with booleans?

Same as with numbers: combine them in expressions.

But the operators are different.

Three logicial operators

AND, OR, and NOT

These are the three operators defined in Boolean Algrebra by our friend George Boole.

And

We’re all used to this. Sally and Joey are both short. Sally is also funny but Joey is not.

Is it true that Sally is short and funny?

Yes.

Is it true that Joey is short and funny?

No.

Writen &&

short && funny

Evaluates to true if, and only if, both of its operands are true.

Or

We’re also used to this. Same as before. Sally is short and funny. Joey is short and not funny. And Sam is tall and not funny.

Is it true that Sally is short or funny?

Yes.

Is it true that Joey is short or funny?

Yes.

Is it true that Sam is short or funny?

No.

Written ||

short || funny

Evaluates to true if either, or both, operands are true.

Not

Another one just like English.

Is it true that Sally is not short?

No.

Is it true that Joey is not funny?

Yes.

Written !

!funny

Flips the logical value, true to false and false to true.

Some examples

Am I hangry?

Suppose hungry is a boolean that says whether I’m hungry and angry says whether I’m angry.

What’s an expression that captures whether or not I’m hangry?

hungry && angry

Do I stay up late?

Suppose homework is a boolean that says whether I have homework to grade and newEpisodes is a boolean that says whethere there new episodes of my favorite TV show available.

What’s an expression that captures whether I will stay up late if I always stay up late to grade homework or to watch new episodes of my favorite show?

homework || newEpisodes

Am I awake?

asleep is a boolean that says whether I’m asleep.

What’s an expression that says whether I’m awake?

!asleep

Remember

Booleans are just another kind of value.