You are on page 1of 40

Conditionals, Operators,

and Loops
Week 3
Course Overview
Current Course Schedule: February 24 to April 21, Thursdays @ 6-7
PM at GDC (check Slack for specific room) and on Zoom (we will
continue to monitor pandemic conditions)

1. Course Overview and Introduction to JavaScript


2. Values, Variables, and Functions
3. Conditionals, Operators, and Loops - Today
4. Timers, Variable Scope, and Code Organization - After Break
5. Object-Oriented Programming
6. Strings, Primitives, Arrays, and Numbers
7. Advanced Object-Oriented Programming
8. ES6, Events, Developer Tools, and Web Programming

Review quizzes/coding exercises after classes


Development Environment Check
● Make sure that you have all the software/tools needed for the
rest of the class this semester:
○ Visual Studio Code (or another code editor)
○ Node.js
○ GitHub account
○ GitHub Desktop
● If you are having trouble downloading one of the tools, let us
know!
Homework Review - Solution on GitHub
● Write a function named sumOfSquareAreas that takes two parameters: a and b,
which each represent the side lengths of two different squares. Return the value of
the sum of the areas of these squares (for example, if a = 9 and b = 3, then we
want to return 90). Then, call this function 3 times with different values for a and b
and output the results to the terminal by running your code.

● Write a function named gradeCalculator that takes three parameters:


homeworkAvg, quizAvg, and examAvg, which each represent your average for
a class on homework, quizzes, and exams, respectively. Return the value of your
overall grade in the class if homework is weighted at 10%, quizzes are 15%, and
exams are 75%. Then, call this function 3 times with different values for
homeworkAvg, quizAvg, and examAvg and output the results to the terminal by
running your code.

● Push this code to your GitHub repository using GitHub Desktop!


Food for Thought
Suppose that we are passing by Moge Tee and we have $10. We could go
in and buy some boba tea, or we could save the money for another day.

How do we decide? On what condition should we consider?

Suppose we know that we are thirsty?


Introducing If/Else Statements
If / else statements are the most common type of conditional statement!
The condition must either be true or false.

if (condition) {
do_something; code to run if condition
is true

} else {

do_something_different; code to run if condition is


false

}
Example of If/Else Statements
Here is an example of an if / else statement.

var isThirsty = true;

if (isThirsty) {
buyMoge();
} else {
saveMoney();
}

*You could also have just an if statement*


Food for Thought
What if we only wanted to buy Moge Tee if we also wanted to buy food?
So… we need to be hungry AND to be thirsty in order to buy food and
boba.

OR

What if we also considered Moge Tee as a meal. So… we could be hungry


OR thirsty in order to convince ourselves to buy boba.
Introducing Logical Operators
Logical operators are used to compare two or more things and return a
final outcome of true or false.

if (expression operator expression) {


do_something;

} else {
do_something_different;

}
List of Conditional Operators
● a == b - tests if the expressions are equal
● a >= b - tests if the first expression is greater or equal to the
second
● a > b - tests if the first expression is greater than the second
● a <= b - tests if the first expression is less or equal to the
second
● a < b - tests if the first expression is less than the second
● a != b - tests if the first expression does not equal the second
● a && b - tests if both expressions evaluate to true (and)
● a || b - tests if either expression evaluates to true (or)
● !== and === - we will look at these later!!!
Examples of Conditional Operators
Example of &&: Example of ||:

var isThirsty = true; var isThirsty = true;


var isHungry = false; var isHungry = false;

if (isThirsty && isHungry) if (isThirsty || isHungry)


{ {
buyMoge(); buyMoge();
buyFood(); } else {
} else { saveMoney();
saveMoney(); }
}
Another Example
The code below checks if someone made an B.

function checkGrade(grade) {
if ( (grade >= 80) && (grade < 90) ) {
console.log(“I made a B!”);
} else {
console.log(“I didn’t make a B…”);
}
}
Longer If/Else Statements: Else If
What if instead of just checking if we made a B, we check what letter
grade we made overall? We can do this by creating longer if / else
statements by introducing else if blocks:

if (condition) {
do_something;
} else if (condition) {
do_something_different;
} else if (condition) {
do_something_different2;
} else {
do_something_different3;
}
Longer If/Else Statement Examples
function checkGrade(grade) {
if ( grade >= 90 ) {
console.log(“I made an A!”);
} else if ( (grade >= 80) && (grade < 90) ) {
console.log(“I made a B!”);
} else if ( (grade >= 70) && (grade < 80) ) {
console.log(“I made a C!”);
} else if ( (grade >= 60) && (grade < 70) ) {
console.log(“I made a D!”);
} else {
console.log(“I failed…”);
}
}
Food for Thought
Let’s think more about how we can make decisions based on certain
expressions.

With what we know so far about if / else if statements, how would I write
a function, numberToMonth, that takes in a number from 1 to 12, and
based on the number, prints out the respective month to the console?

For example, if the number is 3, we would want to print out “March”.


Implementing numberToMonth()
function numberToMonth(number) {
if (number == 1) {
console.log(“January”);
} else if (number == 2) {
console.log(“February”);
}
. . .
} else if (number == 12) {
console.log(“December”);
} else {
console.log(“This is not a month.”);
}

}
Food for Thought
The previous function implementation gets the job done, but it can be
cumbersome to write so many else if statements and also negatively
impacts code readability.

In general, when we have scenarios with several possibilities of what a


variable or expression could equal, we’ll want to use another type of
conditional block…
Introducing Switch Statements
Switch statements are highly similar to if / else if blocks,
except are more concise and cleaner to read. Using switch statements
allows us to avoid repeating the same syntax for an expression
repeatedly, therefore allowing for code reusability.

Switch statements proceed into different cases depending on the value


of an expression. Switch statements aim to find the match between
the value of an expression and the value of a case.

Let’s look at how switch statements are constructed.


Anatomy of Switch Statements
Switch keyword Expression
switch (expression) {
Case keyword case value1:
<code here>
break;
Break keyword
case value2:
<code here>
break;
...
Default keyword default:
<code here>
}
Example of a Switch Statement
function numberToMonth(number) {
switch (number) {
case 1:
console.log(“January”);
break;
case 2:
console.log(“February”);
break;
. . .
default:
console.log(“Not a month.”);
}
}
Another Example
function groceryStore(item) {
switch (item) {
case “Apple”:
console.log(“Apples cost $0.50 each.”);
break;
case “Pear”:
console.log(“Pears cost $0.55 each.”);
break;
. . .
default:
console.log(“We don’t sell this item.”);
}
}
Another Example
function mysterySum(a, b) {
switch (a + b) {
case 3:
console.log(“a + b == 3”);
break;
case 6:
console.log(“a + b == 6”);
break;
default:
console.log(“a + b != 3 && a + b != 6”);
}
}
Food for Thought
We have talked a lot about how we want to avoid code repetition and use
syntax that favors code reusability. We want to make our code clear and
readable.

Let’s say I have the following function:

function happyBirthday() {

console.log(“Happy Birthday!”);

If I want to print “Happy Birthday!” 5 times, what do I do?


Food for Thought
happyBirthday();
happyBirthday();
happyBirthday();
happyBirthday();
happyBirthday();

This gets the job done, but our code suffers from extreme repetition.

Also, what if I want to say “Happy Birthday!” a variable number of times,


like as many times as the number of years old someone is turning
(example: say “Happy Birthday!” 21 times if someone is turning 21)?
Would that be possible with what we know now?
Introducing Loops
Loops are code structures that will run code repeatedly for us!

We have control over how many times the code inside of loops will
run.

Loops are extremely common throughout code in all coding languages


as they are extremely powerful. Frequently, we will need to run code
statements multiple times!

There are three types of loops: for loops, while loops, and do…
while loops. We will cover for and while loops.
Anatomy of a For Loop
Starting
condition with
iteration Terminating How to get
For keyword condition to the end
variable
for (var i = 0; i < count; i++) {
<code here>
}

i++ increments i by 1 after each iteration.

The variable i here is the iteration variable. We use it to keep track of


how many times we have run the loop so far.

Note: We will often start our iteration variables at 0. This will make
more sense later in the course!
Example of a For Loop
Let’s see how the following loop will run in practice:
for (var i = 0; i < 2; i++) {
console.log(i);
}

First iteration: i = 0. Is i < 2?


Yes, since 0 < 2. So, console.log(i) is ran and 0 is printed
to the terminal.
i++. Now i = 1.
Second iteration: i = 1. Is i < 2?
Yes, since 1 < 2. So, console.log(i) is ran and 1 is printed
to the terminal.
i++. Now i = 2.
Third iteration: i = 2. Is i < 2?
No, as 2 < 2 is false. The loop terminates.
Example of a For Loop
var newAge = 21;

for (var i = 0; i < newAge; i++) {


happyBirthday();
}

How many times will we print “Happy Birthday!” to the terminal?

“Happy Birthday!” will print to the terminal 21 times, as i takes on


the values: 0, 1, 2, …, 20
Variable Operators
++ is just one example of an operator that we can use to update variables.
Below is a list of the most common variable operators:

● –- - decrements the value of a variable by 1


● a += x - increments a by x and stores the result in a (a = a + x)
● a -= x - decrements a by x and stores the result in a (a = a - x)
● a *= x - multiplies a by x and stores the result in a (a = a * x)
● a /= x - divides a by x and stores the result in a (a = a / x)
Another For Loop Example
for (var num = 1; num <= 1024; num *= 2) {
console.log(num);
}

What will be the output of this loop to the terminal?

1
2
4
8
...
1024
Anatomy of a While Loop
A while loop will continue to run while its expression is true and will
terminate when the condition is false.

While keyword Expression


while (expression) {

<code here>

}
Example of a While Loop
while (tired) {

sleep();

The while loop will continue to run until tired changes to false.
Another While Loop Example
var newAge = 21;
var i = 0;
while (i < newAge) {
happyBirthday();
i++;
}

This code is analogous to the for loop example we discussed previously.

for loops can be translated into while loops!


Another While Loop Example
while (true) {
console.log(“Hello World!”);
}

What does this while loop do?

The loop will run infinitely, as the expression will never evaluate to false!

We want to always avoid expressing while loops in this way.


Exiting Loops Early
Remember the break keyword for switch statements? break is also
used in the context of loops!

When a break statement is reached, the loop will immediately terminate.


This is similar to how in switch statements when the break statement is
reached we exit the switch statement.
Example of Exiting Loops Early
for (var i = 0; i < 10; i++) {
console.log(i);
if (i == 4) {
console.log(“Let’s exit early.”);
break;
}
}

How many times will this loop run?

The loop will run 5 times (i takes on values of 0, 1, 2, 3, 4).


Conditionals, Operators, and Loops
Demo: Putting it All Together

We’ve learned a lot of new syntax today - if, else, and else if
statements, switch statements, for loops, while loops, logical
operators, and variable operators!

Let’s walk through how we can put these concepts into practice together
by writing a function, walkToTreasure, that takes in x and y
coordinates on a beach and “walks” to the location of the treasure buried
in the sand!
Homework for This Week
● Write a function named countUpwardsByThree that has no parameters. In this
function, use a for loop or while loop to count from 0 to 30 by 3, and output each
number to the terminal as the loop counts (print 0, print 3, print 6, …, print 30). Call
this function once.

● Write a function named guessMyFavoriteNumber that takes in one parameter


named guess. In the function, output “You guessed my favorite number!” to the
terminal if guess is equal to your favorite number (you pick this number), and
print out “Try again!” otherwise. Call this function multiple times.

● Write a function named convertNumberToDay that takes one parameter named


number. In the function, use a switch statement to output the day of the week
associated with numbers from 0 to 6 to the terminal (if number is 0 then output
Sunday, if number is 1 then output Monday, etc.). Call this function 7 times for each
number from 0 to 6.
Next Class!
On March 24th (after spring break), we will be going over timers, variable scope,
and code organization in JavaScript!

Timers
- How can we delay running our code or run code at certain intervals of time?

Variable Scope
- How can variables be accessed across our program?
- How can we limit the access of variables to certain parts of code?

Code Organization
- How can we maintain good program hygiene?
Attendance

You might also like