This lesson introduces conditional statements, a core aspect of programming. You’ve used conditional statements in Scratch so this lesson starts with a review of the basic purpose of conditional statements. After this review, you’ll review JavaScript operators and then work through some examples. Conditional statements are present in nearly every programming language and will greatly enhance the level of interactivity that you’re able to develop and include in your code.
Conditional statements are a crucial part of programming, whether it be for the web, video games or other applications. Conditional statements help programs to make decisions. This is a crucial aspect of creating interactive programs such as games since you can use conditional statements to control what happens if a particular thing happens. You can think of this as a way of making your program branch out based on various choices and events instead of always following one particular path.
You’ve already been using conditional statements throughout this course! The logical structure that you’ve used in Scratch is the same that you’ll be using in JavaScript. The key difference is that you’ll need to become familiar with the JavaScript syntax.
A conditional statement is a set of commands that execute if a certain logical condition is true. Let’s consider an example of this basic concept:
if (x > 10) {
// if true do these things
} else {
// if false do these things
}
Code language: JavaScript (javascript)
In this example, the if statement is evaluating a condition that is contained with the ( ) following the word if. The statement that is within the ( ) needs to be able to be evaluated as a Boolean value, meaning it must either evaluate to true or false.
In the above example, the statement would evaluate as true if the value of the variable x is greater than 10. If this returns true, then the code within the first set of { } is executed.
This particular form includes an else { }
block statement as well. The code inside the { }
executes if the condition (x > 10) is false. Since the statement contained within the ( ) is Boolean, meaning it is either true or false, only one block statement of code will execute.
This is similar to the if → then blocks in Scratch. Take a look at this Scratch block:
The forever loop has been omitted to just highlight the conditional statement. The basic structure, if rewritten into mock JavaScript syntax, would be:
if (keyCode == LEFT_ARROW) {
// change the costume;
// change the sprite's x position by -10
}
Code language: JavaScript (javascript)
The code inside the { } in the above example isn’t actual JavaScript syntax. This is something called pseudo-code that is done to illustrate a concept. You’ll learn how to write JavaScript that responds to keypresses in a later lesson.
Another common form for this is for the else { }
to be excluded:
if (name !== "") {
console.log(`Hello there, ${name}`);
};
Code language: JavaScript (javascript)
This code block would execute only if the content of the name
variable isn’t empty. This structure is commonly used for quick conditional checks, such as the one above.
Another common use is for there to be multiple if statements stacked together using else if. This is usually better than writing multiple if statements because your program will stop looking once it finds the true condition. Let’s take a look at a code snippet:
function keyTyped() {
//keyTyped watches for user pressing letter keys
if (key == 'p') {
//if user types 'p' change color to pink
col = color(255,0,100);
} else if (key == 'g') {
//if user types 'g' change color to green
col = color(0, 255, 200);
}
}
function keyPressed() {
//keyPressed can be used for special characters
if (keyCode == LEFT_ARROW) {
//left arrow changes background to white
bgcol = color(255);
} else if (keyCode == RIGHT_ARROW) {
//right arrow changes background to gray
bgcol = color(50);
}
}
Code language: JavaScript (javascript)
Don’t worry if you don’t understand all of the above syntax right now. Just pay attention to the if…else if
structure. In the example, one thing will happen if the user presses the left arrow, and another thing will happen if the user presses the right arrow.
Now that you have an understanding of the structure of conditional statements, it’s time to introduce another key concept, operators. This section includes some of the basic operators that you’ll use in JavaScript.
You’ve already worked with the first type of operator, which is the assignment operator. These are operators that assign a value to something on the left based on the evaluation of what’s on the right. Here are some examples:
let placeholderName = 'Dave';
const x = 5;
const y = 6;
const result = x + y;
Another type of operator is the comparison operator. This was used in the previous conditional statement example where the value of a “name” variable is checked to see if it is empty.
These are commonly used in if...else statements
because they return true or false based on the evaluation. Many of these are the same as what you’ve likely used in math classes. Here are some examples:
Equal (==)
This returns true if the values are equal.Not equal (!=)
This returns true if the values aren’t equal.Strict equal (===)
This returns true if the value AND the datatype are equal.Strict not equal (!==)
This returns true if the value AND the datatype are not equal.Greater than (>)
This returns true if the value on the left is larger than the value on the right.Greater than or equal to (>=)
This returns true if the value on the left is larger or equal to the value on the right.Less than (<)
This returns true if the value on the left is less than the value on the right.Less than or equal to (<=)
This returns true if the value on the left is less than or equal to the value on the right.One thing that you should remember is that when evaluating equality within conditional statements, you want to use the (==) or (===) operators. If you use only a single (=), JavaScript thinks that you’re attempting to assign a value and it can become confused about how to handle the statement.
There are other operator types that you’ll encounter, but for now, focus on developing an understanding of how these operator types are used with conditional statements to provide control flow to your code.
Now that you have an understanding of the basics of conditionals and operators, let’s take a look at an example in p5.js. As you saw in the variables lesson, p5 provides some extremely useful variables that can track events such as the mouse position. Let’s create something that changes the fill color based on the mouse position on the canvas.
A good first step is to plan out what you want to happen. Let’s do a quick mockup:
Step three requires the use of a conditional statement that checks if the mouse position is at a certain point on the canvas. Let’s now translate this plan into some code! Take a look at this code:
function setup() {
createCanvas(800,800);
strokeWeight(4);
}
function draw() {
// single value for background is gray scale
background(100);
//draws an ellipse at the mouse cursor
ellipse(mouseX, mouseY, 50,50);
if (mouseX < width/2) {
// if the mouse position is on the left half of the screen
fill(255,0,100);
}
else {
// if the mouse is not on the left half of the screen
fill(0,255,100);
}
}
Code language: JavaScript (javascript)
The ellipse is always being drawn at the mouse cursor since mouseX
and mouseY
pass in the current X and Y positions of the mouse. Next, there is a quick conditional to check the position of the mouse.
Remember, width
is a variable that p5 provides, and it’s equal to the width of the canvas. In this case, width
is equal to 800. If the full width
is 800, width/2
would be 400 which is the horizontal center of the canvas.
The conditional then checks to see if the mouse is less than width/2
. This would return true if the mouseX
is on the left half of the canvas. If this is true, then the ellipse fill color is set to pink. If the mouse is anywhere else on the screen, then the code inside the else
block will run, and the fill color is set to green.
Practice: Create your own sketch that integrates at least two conditional statements! Make sure that something happens based on the result!