Main content
AP®︎/College Computer Science Principles
Course: AP®︎/College Computer Science Principles > Unit 3
Lesson 5: ConditionalsConditionals with if, else, and Booleans
As humans, we make decisions every day, like what to eat for lunch or whether to wear a raincoat. When we make those decisions, we consider many conditions of our world, like the contents of our fridge for the lunch decision, or the weather outside for the raincoat decision.
Computer programs also make decisions, using Boolean expressions (true/false) inside conditionals (if/else). Thanks to conditionals, programs can respond differently based on different inputs and parameters.
A simple conditional
Imagine we're writing a program to help us decide what to wear outside each day. There are a lot of conditions we can come up with this program, but let's start simple: if the temperature is below freezing, the program should warn us to wear a snow jacket.
Here's that logic in a flowchart:
We can program that flow in JavaScript using an if statement:
if (temperature < 32) {
println("Wear a snow jacket!");
}
Let's breakdown that syntax. The general structure of every if statement looks like this:
if (<condition>) {
<instructions>
}
The condition and instructions are what differ; that's where the magic happens.
The condition is a Boolean expression: an expression that evaluates to either
true
or false
. Boolean values are another type of data type in programming languages, and they can only ever hold true or false. For example, we can store the results of that Boolean expression in a variable:
var belowFreezing = temperature < 32;
Depending on the current value of
temperature
, the belowFreezing
variable will now store either true
or false
.We can even substitute the condition with the variable:
var belowFreezing = temperature < 32;
if (belowFreezing) {
println("Wear a snow jacket!");
}
However we code it, the condition needs to evaluate to either
true
or false
, because that tells the computer whether to execute the instructions inside the curly brackets or not.The instructions can be anything your program is capable of doing, and they can be as long as necessary.
✏️ Try changing the value of
temperature
in the program below and see what happens. You can also change the condition or the instructions.Note: typically, a program like this would read the value of
temperature
from a sensor or other input device, but for simplicity, we're hardcoding the value into the program.Comparison operators
Our Boolean expression above used the comparison operator
<=
to determine whether one number is less than or equal to another number. There are many comparison operators in programming languages to determine different relationships between values, especially numbers.Here are the relational operators in JavaScript:
Operator | Meaning | True expressions | |
---|---|---|---|
> | Greater than | 60 > 32 | |
>= | Greater than or equal | 60 >= 32 | 32 >= 32 |
< | Less than | 20 < 32 | |
<= | Less than or equal | 20 <= 32 | 32 <= 32 |
=== | Strict equality | 32 === 32 | |
== | Equality | 32 == 32 | "32" == 32 |
!== | Strict inequality | 30 !== 32 | "32" !== 32 |
!= | Inequality | 30 != 32 |
JavaScript is a bit of a tricky language here, because it has both equality operators and "strict" equality operators.
The equality operators will first try to force both sides of the expression to be the same type (like by converting them both to numbers), and then check for equality. The strict equality operator will see that two values are different types and immediately decide they can't possibly equal each other. We recommend using the strict operators because they lead to more predictable code.
Most programming languages do not have both types of equality operators, but you may encounter other differences in the way that languages decide if two variables are equal.
✏️ The program below displays all sorts of messages based on the
yourAge
variable. Try changing that to different values to see what output is displayed. You can also add more if
statements to the program.The else statement
With if statements, our programs can execute a set of instructions only if the condition is true. If we want our programs to execute a different set of instructions when the condition is false, then we can use an else statement.
Imagine a super simple password checking program. The logic flow looks like this:
We can program that using an
if
statement followed by an else
statement:if (password === "TOPSECRET") {
println("You got it!");
} else {
println("Try again!");
}
Our program is guaranteed to always go down one of the two paths: either the condition is true and it goes down the first path, or it's false and it goes down the second path.
Conditionals in pseudocode
This pseudocode represents a single
if
statement:IF (<condition>)
{
<instructions>
}
This pseudocode includes an
else
statement with a second set of instructions that can be executed instead:IF (<condition>)
{
<instructions 1>
}
ELSE
{
<instructions 2>
}
These are the relational operators in pseudocode:
Operator | Meaning |
---|---|
a = b | Equality |
a ≠ b | Inequality |
a > b | Greater than |
a < b | Less than |
a ≥ b | Greater than or equal |
a ≤ b | Less than or equal |
Here's the password checker logic in pseudocode:
IF (password = "TOPSECRET")
{
DISPLAY("You got it!")
}
ELSE {
DISPLAY("Try again!");
}
🙋🏽🙋🏻♀️🙋🏿♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!
Want to join the conversation?
- What does "JavaScript is a bit of a tricky language here, because it has both equality operators and "strict" equality operators.
The equality operators will first try to force both sides of the expression to be the same type (like by converting them both to numbers), and then check for equality. The strict equality operator will see that two values are different types and immediately decide they can't possibly equal each other. We recommend using the strict operators because they lead to more predictable code," mean?(3 votes)- There are two equality operators in JavaScript, the "equality operator" (==) and the "strict equality operator" (===). The equality operator will attempt to convert operands that are different types so that it can compare them. For example,
'10' == 10
will evaluate to true, whereas'10' === 10
will evaluate to false.
The first part of the example uses the equality operator, which will perform an implicit conversion to compare two elements of differing types. In this case, we compared a string ('10') and a number (10), and after conversion they were found to be equivalents.
The second part of the example uses the strict equality operator, which does not perform implicit conversion. The strict equality operator compares the values of the elements and their data types. In this situation, since the data types did not match (we compared a string and a number) they were found to not be equivalents.(9 votes)
- Hey!
Shouldn't the password checker logic in pseudocode be as follows?
IF (password = "TOPSECRET")
{
DISPLAY("You got it!")
}
ELSE
{
DISPLAY("Try again!")
}(1 vote) - If I copy the code that is in khan academy and paste it into visual code, it doesn't work. Could you tell me why please ?(0 votes)
- The code above is represented in a pseudocode format, so it does not translate directly over to JavaScript. You will need to make slight modifications to the code to run it using VSCode (e.g. change
println()
statements toconsole.log()
statements).
Also, the execution of JavaScript relies on an interpreter in the browser reading and interpreting each line of the code. Therefore, it is a tad difficult to run JavaScript directly in VSCode. You will need a JavaScript runtime environment (i.e. Node.js) that, once installed, will allow you to run JavaScript programs through VSCode by runningnode <program_name.js>
in VSCode's built-in terminal.(2 votes)
- Aren't the strict and regular inequality examples in the operator table are wrong here?(0 votes)
- How do nested if statements work?(0 votes)
- The computer reads each one like it did the last. If the outer condition is true, then the code inside the
if
statement is run. If the condition for the inner statement is true, then the code inside thatif
statement is run. If it's false, it runs the remaining code inside the outerif
statement. If the outer condition is false, then the inner one will never be reached, as the computer skips over it.(0 votes)
- i dont the inequality button so what to do?(0 votes)
- The inequality operator is two separate characters, an exclamation point (!) and an equals sign (=). Type the two characters individually, one after another to yield !=.
If you do not have access to these characters, you might need to change your keyboard configuration (however since you composed your question with characters from the alphabet for Modern English and a question mark, your current configuration should be okay).
If you exhaust all other options, then you can highlight the inequality operator used in the article and copy & paste it as necessary - this approach is inefficient, so see if the approaches above work first.(0 votes)
- (environmental policy)and(environmental AND policy)will retrieve what kind of results?(0 votes)
- Hello, how can you use the output of the first try if statement to then is used to make the second if statement true?
if (clb1 == 68) { // yellow
clb1 = (231);
clb2 = (114);
clb3 = (42);
}
if (cbl1 == 231) { // light blue
clb1 = 70;
clb2 = 60;
clb3 = 121;
}
if (cbl1 == 231){ // yellow
clb1 = 68;
clb2 = 60;
clb3 = 117;
}
}(0 votes)- You can nest
if
statements, so if the outer condition is true, then the inner condition will be run.(0 votes)
- What kind of statement do you make if the condition turns out false?(0 votes)
- In algorithm, think we use ELSE if the condition is false
(e.g. IF (a>b)
{
DISPLAY ("a is more than b")
}
ELSE <- This means that if the condition is false
{
DISPLAY ("a is less than b")
}
)(0 votes)
- What are booleans and why is it related to boolean algebra?(0 votes)
- The Boolean data type is used to represent one of two possible values: true or false. Boolean algebra is a branch of algebra where the variables represent the same: true or false.
The Boolean data type is essential for understanding branching (and conditional expressions) in your code, and boolean algebra can be helpful for a myriad of courses in computer science.(0 votes)