Main content
Computer programming
Course: Computer programming > Unit 1
Lesson 11: Logic and if Statements- If Statements
- Challenge: Bouncy Ball
- More Mouse Interaction
- Challenge: Your First Painting App
- Booleans
- Challenge: Number Analyzer
- Logical Operators
- Challenge: Your First Button
- Challenge: Smarter Button
- If/Else - Part 1
- Challenge: Flashy Flash Card
- If/Else - Part 2
- Review: Logic and if Statements
- Random numbers
- Project: Magic 8-Ball
© 2023 Khan AcademyTerms of usePrivacy PolicyCookie Notice
Review: Logic and if Statements
This is a review of what we covered in this tutorial on logic and if statements.
We often want to be able to "conditionally" do things in our programs - we want to be able to say "if this thing is true, then do X but if this other thing is true, then do Y." It's like when we wake up in the morning - "if it's raining outside, then I take an umbrella, but if it's sunny, I wear sunglasses." We can do things conditionally in our programs using if statements and if/else statements combined with conditional expressions.
An if statement tells the program to execute a block of code, if a condition is true. In the code below, we output a message only if
x
is greater than 0:var x = 5;
if (x > 0) {
text('x is a positive number!', 200, 200);
}
Since x is 5, which is greater than 0, we would see the message on the canvas. If we changed x to -1, we wouldn't see the message show up at all, since x wouldn't be greater than 0.
The
x > 0
is what we call a conditional expression - which means it's an expression that evaluates to either true
or false
. When a value is either true
or false
, we call it a boolean value (as opposed to a number or a string). For example, we could just display the conditional expression:text(x > 0, 200, 200); // Displays "true"
We could also store it into a variable and then display it:
var isPositive = x > 0;
text(isPositive, 200, 200);
We would then say that
isPositive
is storing a boolean value, because it's either true
or false
, depending on what we set x to.We have many ways of creating conditional expressions that will evaluate to
true
or false
, because we have many comparison operators. Here are the most popular:Assuming the following variable, here are the most common comparison operators and expressions that would be true with them:
var myAge = 28;
Operator | Meaning | True expressions | |
---|---|---|---|
=== | Strict equality | myAge === 28 | |
!== | Strict inequality | myAge !== 29 | 28 !== 29 |
> | Greater than | myAge > 25 | 28 > 25 |
>= | Greater than or equal | myAge >= 28 | 28 >= 28 |
< | Less than | myAge < 30 | 28 < 30 |
<= | Less than or equal | myAge <= 28 | 28 <= 28 |
It is a very common mistake to confuse the assignment operator (
=
) with the equality operator (===
), because they both use equal signs, but they are quite different. The assignment operator will actually change the value of the variable, whereas the equality operator will just read the value of the variable and see if it's equal to something. For example:var x = 2 + 2; // Sets it equal to 4
if (x === 4) { // Asks the question, "does this equal 4?"
text("yep, 2 + 2 = 4!", 200, 200);
}
We sometimes want to combine multiple comparisons together in a conditional expression, and that's why we have logical operators. These operators let us say things like "if both X and Y are true" or "if either X or Y are true" in our programs.
If we want to require that two conditions are both true, we can use the
&&
operator ("and"):var degreesOutside = 70;
var numberOfClouds = 50;
if (degreesOutside > 70 && numberOfClouds < 5) {
text("Wear sun screen!", 200, 200);
}
We often use that in our programs here for checking that a user's mouse position is inside a rectangle (to mimic a button), in which case we need multiple
&&
operators:rect(100, 50, 100, 100);
mousePressed = function() {
if (mouseX > 100 && mouseX < 200 && mouseY > 50 && mouseY < 150) {
text("You pressed it!", 80, 75);
}
};
If we only care that at least one condition is true, then we can use the
||
operator ("or"):var degreesOutside = 70;
var numberOfClouds = 50;
if (degreesOutside > 70 || numberOfClouds < 5) {
text("Wear sun screen if it's hot outside or there aren't many clouds!", 200, 200);
}
We can use both
&&
and ||
in the same expression, if we have some very complex condition to check. Just use parentheses to group expressions, so that the program isn't confused about what order to evaluate them:var myAge = 28;
if ((myAge >= 0 && myAge < 3) || myAge > 90) {
println('You\'re not quite in your peak.');
}
Now let's return to if statements. We often want to execute some block of code in the case that the if condition wasn't true - in that case, we add an else statement.
var age = 28;
if (age > 16) {
println('Yay, you can drive!');
} else {
println('Sorry, but you have ' + (16 - age) + ' years until you can drive.');
}
Sometimes we want to check multiple conditions, and do different things based on each, in which case we can use
else if
:var age = 20;
if (age >= 35) {
println('You can vote AND hold any place in government!');
} else if (age >= 30) {
println('You can vote AND run for the Senate!');
} else if (age >= 18) {
println('You can vote!');
} else {
println('You have no voice in government!');
}
You can keep checking conditions as much as you want - just make sure that each of your conditions is actually reachable. Test your code by changing variables until you make it inside each of the blocks of code, so that you know it all works.
As you can hopefully now see, conditionals are an important part of programming and let us create much more powerful and flexible programs.
Want to join the conversation?
- I thought " ! == " meant "does not equal". But how can 28 not equal 28? Or do the quotation marks change '28' somehow?(67 votes)
- 28 is an integer. '28' is a string.(172 votes)
- If I don't remember anything could I start all over again ?(25 votes)
- Go for it! It will probably be easier to learn this time, too.(47 votes)
- is there any different between website and webpage? when can I create a website?(8 votes)
- A webpage is a single page on a website, like https://www.khanacademy.org/computing/computer-programming/programming/logic-if-statements/a/review-logic-and-if-statements whereas a website is a grouping of one or more webpages, like khanacademy.org(50 votes)
- I haven't done this in a couple of weeks, so I'm kind of lost. Could someone dumb this down please. Or should I just re watch all the videos again.(9 votes)
- There's no shame in watching the videos of this section again. They're not too long, so it should be ok.
If you still have questions after that, we're of course happy to help.(30 votes)
- I find it strange that we would have to write x > 50 && x < 100. Why can't I just use 50 < x < 100?(9 votes)
- JavaScript interprets conditionals differently than humans normally write inequalities. Going left to right, JavaScript interprets
50 < x
as one conditional, evaluating to eithertrue
orfalse
. It then compares that result to100
(convertingtrue
to1
orfalse
to0
, to make a valid comparison).0
and1
are both less than100
, so50 < x < 100
will always betrue
.
Avoid writing multiple inequalities the way you would normally do in math – the computer will take it too literally.(27 votes)
- Is there an exclusive 'or' operator? There's a bit of logic in a program I'm working on that doesn't work particularly well with '||', since it's inclusive(6 votes)
- Simply
!==
is Exclusive-OR if both the operands are booleans, and less dangerous than the bitwise operator.
Or, with complete Javascript coercion, tryvar xor = function(a, b) {
a = !!a;
b = !!b;
return a !== b;
};(11 votes)
- okay so here's another question how do I make the drops fall at different times instead of falling in a line?(6 votes)
var yPositions = [random(-50, 30), random(-50, 30), random(-30, 50)];
What this does is it distributes theyPositions
in such a way that some drops will START above the canvas and eventually leak out. This is what I did and it worked. For every drop you want, add arandom(-50, 30)
to thearray[];
. If you want to make them a lot more spaced outy
wise, then you can expand the numbers in thearray[];
(8 votes)
- what is the difference between println and text?(3 votes)
- Text creates text on the screen. Println creates an element, where text is printed onto. You can't customize the appearance of a println, but you can change the color, size, and font of text.(10 votes)
- And another question - why should the command "fill" be inserted before rather than after the "if" statement? On the canvas I see no difference with the order switched, so is there any profound reason behind what I see?(4 votes)
- If the same fill is needed in all conditions in the if statement it makes sense to just set it once before. If again the fill is different depending on the conditional you set it inside.(7 votes)
- For the "!==" operator, which way is the strict inequality pointing? And also how is !== different from < or > ?(4 votes)
- "Which way is the strict inequality pointing? "
I did not know that inequality was asymmetric! Can you give me an example where a≠b, but is it not the case that b≠a?
"How is !== different from < or > ?"
Well, 7≠10, but it is not the case that 7>10. Similarly 10≠7, but it is not the case that 10<7.(x !== y)
can be rewritten as((x < y) || (x > y))
.(2 votes)