If Statements

If Statements
January 19, 2017
If Statements

An if statement tells the program whether or not to run a piece of code
depending on whether a certain condition is met.


These are also called conditional statements.
The condition is called a conditional expression—it is either TRUE or FALSE.


If the expression is TRUE, the program will run the following code.
If the expression is FALSE, the program will skip it.
if(count == 20) {
setScreen("gameOver");
}
If Statements

One very common if statement/code you will see on the AP exam:
IF (CAN_MOVE (forward))
{
MOVE_FORWARD ()
}
ROTATE_LEFT ()

Remember: An if statement is NOT the same as a loop!

The program will evaluate the conditional statement once.
Comparison Operators

== “is equal to”

!= “is not equal to”

> “is (strictly) greater than”

< “is (strictly) less than”

>= “is greater than or equal to”

<= “is less than or equal to”

The AP exam will use > and <.
Comparison Operators

(2 + 2) == 4 evaluates to TRUE.

"Joe Perry" == "joe perry" evaluates to FALSE (strings are casesensitive).

17 >= (5 + 10) evaluates to TRUE.

"Ringo" <= "Ringo" evaluates to TRUE.

"TGOD" != "tgod" evaluates to TRUE.
Comparison Operators

N.B. "3" == 3 evaluates to TRUE, even though the number is a string.

JavaScript includes a “strict equality” operator, ===, which check to see that both
the value and type are equal.

"3" === 3 evaluates to FALSE.
If-Else Statements

An if-else statement is giving an “either-or” command: either the code
in the if block or the code in the else block will execute.
This is accomplished by adding an else block after the if block:
var band = prompt("What is your favorite band?");
if(band == "Aerosmith") {
console.log("Good answer.");
}
else {
console.log("Try again.");
}

If-Else-If Statements

An if-else-if statement allows you to nest multiple if statements.

For instance, suppose you want the if block to execute if a == 1 or a == 2.

We will learn a simpler way to do this using Boolean operators in time…
If-Else-If Statements
var band = prompt("What is your favorite band?");
if (band == "Aerosmith") {
console.log("Good answer.");
}
else {
if (band == "Tom Petty and the Heartbreakers") {
console.log("Good answer");
}
else {
console.log("Try again.");
}
}