If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

# Conditionals with if, else, and Booleans

AP.CSP:
AAP‑2 (EU)
,
AAP‑2.E (LO)
,
AAP‑2.E.1 (EK)
,
AAP‑2.E.2 (EK)
,
AAP‑2.H (LO)
,
AAP‑2.H.1 (EK)
,
AAP‑2.H.2 (EK)
,
AAP‑2.H.3 (EK)
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:
Flowchart that starts with diamond that says "Is temperature less than or equal to 32?". Diamond has arrow labeled "TRUE" that leads to rectangle that says "Display: "Wear a snow jacket!".
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.
📝 See similar code in: App Lab | Snap | Python
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:
OperatorMeaningTrue expressions$\,$
>Greater than60 > 32
>=Greater than or equal60 >= 3232 >= 32
<Less than20 < 32
<=Less than or equal20 <= 3232 <= 32
===Strict equality32 === 32
==Equality32 == 32"32" == 32
!==Strict inequality30 !== 32"32" !== 32
!=Inequality30 != 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.
📝 See similar code in: App Lab | Snap | Python

## 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:
Flowchart that starts with diamond that says "Is password equal to TOPSECRET?". First arrow is labeled "TRUE" and leads from diamond to rectangle that says "Display: 'You got it!'". Second arrow is labeled "FALSE" and leads from diamond to rectangle that says "Display: 'Try again!'".
We can program that using an if statement followed by an else statement:
if (password === "TOPSECRET") {
println("You got it!");
} else {
println("Try again!");
}
📝 See similar code in: App Lab | Snap | Python
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.
✏️ The program below builds on the earlier age checking program, adding else statements everywhere. Now you can easily see what you can and cannot do at any age. Fiddle with the yourAge variable and see how the output changes.
📝 See similar code in: App Lab | Snap | Python

## 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:
OperatorMeaning
a = bEquality
a ≠ bInequality
a > bGreater than
a < bLess than
a ≥ bGreater than or equal
a ≤ bLess than or equal
Here's the password checker logic in pseudocode:
IF (password = "TOPSECRET")
{
DISPLAY("You got it!")
}
ELSE {
DISPLAY("Try again!");
}

## 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?
• 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.
• Hey!

Shouldn't the password checker logic in pseudocode be as follows?

{
DISPLAY("You got it!")
}
ELSE
{
DISPLAY("Try again!")
}
• 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 ?
(1 vote)
• 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 to console.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 running node <program_name.js> in VSCode's built-in terminal.
• How do nested if statements work?
(1 vote)
• 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 that if statement is run. If it's false, it runs the remaining code inside the outer if statement. If the outer condition is false, then the inner one will never be reached, as the computer skips over it.
(1 vote)
• i dont the inequality button so what to do?
(1 vote)
• 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.
(1 vote)
• Aren't the strict and regular inequality examples in the operator table are wrong here?
(1 vote)
• (environmental policy)and(environmental AND policy)will retrieve what kind of results?
• 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;
}
}
(1 vote)
• You can nest if statements, so if the outer condition is true, then the inner condition will be run.
• What kind of statement do you make if the condition turns out false?
(1 vote)
• 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")
}
)