3:3 Making decisions
We can make deicisions in code with condtionals. They are ways of asking questions and getting different results, not nearly as complicated as it sounds!.
Conditional statements
Conditional statements are used to perform different actions based on different conditions.
There’s a few different kinds:
if
else
if else
switch
The if statement
Let’s focus on the if statement
The if statement runs a bit of code if the condition is true.
if (condition) {
// run this code
}
Those slashes are an actual code thing - they stop that line doing anything. Its called a comment and is often used to add helpful comments into the code (but sometimes to just stop a line working when we're testing stuff).
Operators
conditional statements use different operators.
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
* there actually more
** notice that equal to is not a single equal.
*** more strict code uses triple equal signs (lets not worry about that for now, but you'll see it out there in the wild!)
Using an if statement
An if statement allows us to make decisions about that circle and get it back on the screen.
We need to ask a question - has the circle left the screen.
Then make a decision - please give it back!
// if the xPosition is greater than 400
// we will set it back to zero
if(xPosition > 400) {
xPosition = 0;
}