JavaScript conditional statements and loops

Conditional Statements and Loops Overview

  • Understanding Control Flow
  • Conditional Statement Syntax
  • Equivalency Operators
  • Logical Operators
  • Loops Introduction
  • For Loops

Reading Assignment

Please read Chapter 4

javascript textbook cover

Imagine . . .

1. What functionality would a web store need in order to display inventory that is in stock?

2. As you type a word into a search engine's search box, what makes the predictions appear below the characters you have typed?


Takeaway:

We need programs to take in and respond to user input.

What programs need

1. Ways to see if the program is working under certain conditions

2. Ways to make our programs responsive to the user

Happy Puppy

What Programs Need: Booleans

A boolean can only have two values:
TRUE or FALSE;
YES or NO.

Programs love booleans because:

  • If a condition is TRUE, the program will execute a certain set of instructions.
  • If a condition is FALSE, then the program will execute a different set of instructions.

Conditional Statements

Conditionals allow you to use a user's input to change the results of a program or statement.

All conditions, no matter how complex, can and must be broken down to YES or NO, TRUE or FALSE.

Video Game Example:

  • YES, TRUE: If your user destroys all 10 alien spaceships in your game, your program will allow them to move on to the next level.
  • NO, FALSE: If your user destroys less than 10 alien spaceships in your game, your program will keep them on the current level.

Conditional Statements: More Examples

Voting

If a user is registered to vote, they can vote.
If not, they can sign up to vote.

Weather

If it is pouring, I want to use an umbrella.
If not, I want to use a hoodie.

Sorbet

If hot outside, I want a sorbet.
If not, I want to skip the treat.

In pictures

Control Flow

The blue arrows in the picture illustrate "Control Flow", the conditional flow of program execution.

Based on user inputs to the program, different code will run.

The word "block" refers to code being called in response to the condition. "Code block" is synonymous with "block."

In-Class Exercise

On the board or virtual chat,
write an example of control flow:

  • in real life
  • for a website that you regularly use

Conditional Statements and Loops Overview

  • Understanding Control Flow
  • Conditional Statement Syntax
  • Equivalency Operators
  • Logical Operators
  • Loops Introduction
  • For Loops

Conditional Statements

Dissect the phrase: "conditional statement"

A very simple conditional statement: (the one we will start with) is If something is true, then do this.


if ( the condition ) {
//the code that runs if the condition is true, called a code block
}   

Note! There is no semi-colon at the end of the closing curly brace of the conditional statement.

Relational Operators

Relational operators compare its operands (values on either side of operator) and return a Boolean value.

< Less than operator.
> Greater than operator.
<= Less than or equal operator.
>= Greater than or equal operator.

The if statement

Use if to tell JS which statements to execute, based on a condition.


var x = 5;

if (x > 0) {
  console.log('x is a positive number!');
}

An 'if' statement tests a condition to see if it is true.
If condition is true, the code inside the 'if' statement is run.
Since the value of 'x' is 5, and 5 is greater than 0, the condition is evaluated as true and the code inside our 'if' statement is executed.

The if and else statements

If/Else Control Flow

In pictures

If/Else with print statement

The picture helps us understand a more complex
Control Flow.

Instead of just testing if a condition is true, we have:

  • a block of code to run if it is true and
  • a block of code to run if it is NOT true (false)

The "else" statement is a program option if the main condition tested is "false". The else statement is the "catch-all."

If and else statements: Example

Explore what the following code does.

            
var answer = prompt("What is your favorite number?");
if ( answer > 10 ) {
  alert("You like large numbers!");
} else {
  alert("You like small numbers!");
}
//only one message will appear 

See it in action here.

Another example

Explore what the following code does.

            
var answer = prompt("What programming language is the name of a gem?");
if ( answer === "Ruby" ) {
  alert("Correct!");
}
//If you want an option for if the person gets it wrong
else {
  alert("That’s not right!");
}
//only one message will appear 

1. Enter "ruby" to see what alert appears. Why?

2. Enter "Ruby" to see what alert appears. Why?

See it in action here.

Conditional Statements and Loops Overview

  • Understanding Control Flow
  • Conditional Statement Syntax
  • Equivalency Operators
  • Logical Operators
  • Loops Introduction
  • For Loops

Why so many equal signs?

value1 === value2

Three equal signs is an equality operator that tests if two values, also called operands, have the same value and data type.

If so, the operands are considered to be "strictly equal."

Only if the values and the data types are the same, then the condition is TRUE and the code inside the curly braces in the if block runs.

Exact equivalence example

Explore what the following code does.

       
var answer = prompt("What is the current month?");
if ( answer === "May" ) {
  alert("This is such a great month!");
} else {
  alert("This is an okay month.");
}

See it in action here.

Favorite Food Exercise

  • Create a variable called favoriteFood and give it the value of prompt(“What is your favorite food?”).
  • Create a conditional statement so that if the user answers your favorite food, they get an alert that says “Mine too!”. If they don’t, they get an alert that says “Ewwww”.
  • Make sure that the user can enter their answer in any capital letters or non-capital letters.
Exercise Time Trello Logo

More on operators

Use these operators to compare two values for equality, inequality, or difference.

  
var myAge = 28;
Operator Meaning True expressions
== Equality myAge == 28
myAge == '28'
28 == '28'
=== Strict equality myAge === 28
!= Inequality myAge != 29
!== Strict inequality myAge !== '28'
28 !== '28'
> Greater than myAge > 25
'28' > 25
>=Greater than or equal myAge >= 28
'28' >= 25
< Less than myAge < 30
'28' < 30
<= Less than or equal myAge <= 28
'28' <= 28

Common mistake: Do not confuse = (the assignment operator) with ==.

Exact equivalence

In an earlier JavaScript example, different alerts appeared for the user inputs of “ruby” and “Ruby”.

How do we eliminate the need for a capital case word?

A solution

         
if ( answer.toUpperCase() === "RUBY" ) {
  alert("Correct!");
}

This will make the user's answer correct, no matter the case!

Exercise

Let's say you have a website that requires parental approval for the creation of user accounts.

A visitor who is under or equal to 18 years old will be denied access to your site.

How would you write that in JS?

Practice here.

Operators

Using numbers as the data type, think of some examples which will make the number comparison TRUE and FALSE.

Operator
<
>=
<=
===
!==
True False
5 < 10 10 < 5
10 >= 9 9 >= 10
9 <= 9 10 <= 9
100 === 100 100 === 101
0 !== 1 0 !== 0

Remember

  1. Remember 100>100 is false, BUT 100>=100 is true.
  2. -12 < 0 is correct because negative numbers are less than zero.
  3. Numbers are always less than letters.
  4. What do you think happens if you say: “apple”<“bear”
  5. What about just two ==? (Just value, not type and value)
  6. !== means that two things are not equal in type or value; you can test for that too! (ex: 10 !==9)

True or false

“javascript”===“JavaScript”

false

True or false

“3”===3

false

True or false

“lion” > “zebra”

false

True or false

“lion” !== “zebra”

true

True or false

1000 <= 1000

true

Can there be things besides true/false?

JavaScript has to be able to deal with values that are not exactly "true" or "false"

People call these Truthy and Falsey values

What will this evaluate to?

  
var a = 10;
if (a) {
  alert("yaaaay!");
} else {
  alert("boooo!");
}   

Truthy and Falsey

"Falsey Values": these will evaluate to false if they are in the conditional statement

  • 0
  • -0
  • NaN
  • " "
  • false
  • null
  • undefined

Truthy and Falsey

  
var a;
if (a) {
  alert("yay!")
} else {
  alert("boooo!")
}  

Will the code block run?

If so, which code block will run?

Beyond if and else statements

What if we needed a third option, a Door #3?

If/Else Control Flow

Conditional Statements and Loops Overview

  • Understanding Control Flow
  • Conditional Statement Syntax
  • Equivalency Operators
  • Logical Operators
  • Loops Introduction
  • For Loops

Programming Multiple Outputs

Oftentimes, we have more than one input or condition, and therefore, will need more outputs.

Example: If it is sunny and warm, you can go to the beach. But if it is warm and raining, you will probably stay in.

Control Flow Multiple Outputs

in pictures

Control Flow Multiple Outputs

See it in action here.

A control flow with multiple outputs in real life is the stoplight!

No limit to the number of else if statements that you can have in your code!

  
var isTeacher = prompt("Are you a teacher?");
var isStudent = prompt("Are you a student?");
var isAdministrator = prompt("Are you an administrative staff?")
if ( isTeacher.toUpperCase() === "YES" ) {
    alert("Welcome Teacher");
}
else if (isStudent.toUpperCase() === "YES") {
    alert("Welcome student");
}
else if (isAdministrator.toUpperCase() === "YES") {
    alert("Welcome staff");
}
else {
    alert("Who are you?");
}

Notice: Else statements are the catch-alls for the if and else if statements. Else statements appear at the end.

See it in action here.

Multiple Outputs

Let's look at each line of code and explain it.

        
var itemToBuy = " ";
var savings = 100;
if ( savings > 500 ) {
  itemToBuy = "Computer";
} else if ( savings > 200 ) {
 itemToBuy = "Phone";
} else if ( savings > 0 ) {
 itemToBuy = "Dinner";
} else {
 itemToBuy = "...still saving...";
}

What is the value of the variable itemsToBuy?

Exercise: Time Clock

  1. Create a variable called time and set it equal to the time that the user answers when you ask “What time is it?”
  2. Create an if statement so that if the time is less than 10, the user will be greeted with a “Good Morning!” **NOTE: We are using military time.
  3. If the time is less than 20, the user should be greeted by a “Good Afternoon!”.
  4. If the answer is anything else, the user should be greeted by a “Good Evening!”.
Exercise Time Trello Logo

Explaining Code

It is really helpful to practice explaining code, especially code that you have not written.

If you can explain code, your ability to write code greatly increases!

You got this

Another exercise

Explain each line of code, what the line of code is doing.

  
var cupcakesSold = Number(prompt("How many cupcakes were sold today?"));   
var profitMargin = 30;
if ( cupcakesSold < profitMargin ) {
  alert("Gotta sell more!");
}
else if (cupcakesSold == profitMargin) {
  alert("Broke even!");
}
else {
  alert("We are doing well!!!");
}

Another exercise

Explain each line of code, what the line of code is doing.

 
var wholesalePrice = 5.45;
var retailPrice = 9.99;
var quantity = 47;
var salesTotal = retailPrice * quantity;
var profit = salesTotal - (wholesalePrice * quantity);
if ( profit > 400 ) {
  console.log("Time to go home");
}
else {
  console.log("Keep working");
} 

Logical Operators Intro

What if we only want to find all people who are over 65 AND retired?

What if we only want teens who like chocolate OR tweens who like strawberry?

What if we want French vanilla ice cream, NOT plain vanilla?

Logical Operators

Logical operators are often used with comparison operators:

 
var posNum = 4;
var negNum = -2;
Operator Meaning True expressions
&& AND posNum > 0 && negNum < 0

4 > 0 && -2 < 0
|| OR posNum > 0 || negNum > 0

4 > 0 || -2 > 0
! NOT !(posNum === negNum)

!(posNum < 0)

When combining together multiple conditions, use parantheses to group:

 
var myAge = 28;
if ((myAge >= 0 && myAge < 3) || myAge > 90) {
  console.log("You are either under 3 or over 90.");
}

And Operator

All conditions have to evaluate as true for the program to run.

Example: You need to be near a pool AND know how to swim in order to go swimming.

 
var nearPool = true;
var canSwim = true;
if ( nearPool === true && canSwim === true ) {
  alert("Welcome!");
}

We use && in order to have both of the if conditions met. You put one condition on either side of the &&.

 
var age = 30;
var language = "JS";
if ( age > 18 && language === "JS" ) {
  alert("Welcome, Coder!");
}

And Operator

Another example:

You can have more than one set of &&.

 
var age = 30;
var language = "JS";
var favDanceMove = "The Robot";
if ( age > 18 && language === "JS" && favDanceMove === "The Robot" ) {
  alert("Welcome!");
}

Or operator

One of the conditional statements has to evaluate as true for the program to run.

Example: You need to be near a pool OR near the beach in order to go swimming.

 
var nearPool = true;
var nearBeach = false;
if ( nearPool === true || nearBeach === true ) {
  alert("Welcome!");
}

We use || in order to have both of the conditions met. You put one condition on either side of the ||.

 
var agree = prompt("Do you agree?");
if ( agree === "Yes" || agree === "Y" ) {
  alert("Welcome!");
}

What will appear in the browser's console?

 
var ships = 10;
var score = 0;
if ( ships === 0 || score === 0 ) {
  console.log('Game over.');
}  else {
  console.log('Your score is zero.');
}

What will appear in the browser's console?

 
var x = 10;
var y = 20;
if (  x < 10 && y > 10 ) {
  console.log('The condition passes.');
} else {
  console.log('The condition fails.');
}

And/Or Operators: Make Up Your Own

Pair up to think of some real-world situations where you would need:

  1. both conditions to be true (&&)
  2. either condition to be true (||)
  3. three or more conditions to be true (&&)
  4. one of three conditions to be true (||)

Example: gym membership, hiking tour, boat ride, shipping costs, etc.

Now we will split into four groups. Group 1 will flesh out code for Q1; Group 2, Q2; Group 3, Q3; Group 4, Q4.

Can I go out?

 
var hoursOfWork = 2;
var today = 'Friday';

if ( hoursOfWork >= 10 && today === 'Friday' ) {
  alert("Too much work! I can’t go out");    
} 
else if ( hoursOfWork >= 5 && today === 'Friday' ) {
  alert("I will catch up with you when I can");    
}
else if ( hoursOfWork === 2 && today === 'Friday' ) {
  alert("It's Friday, let’s go!");   
} else {
  alert("This isn't Friday. I need to stay home.");
}

Which mode of transportation?

 
var milesLeft = 9;
var primetime = false;

if ( milesLeft >= 20 || primetime === false ) {
  alert("Awesome. I can drive.");    
} 
else if ( milesLeft >= 10 && primetime === true ) {
  alert("I better bike, scooter or take the bus.");    
}
else if ( milesLeft >= 0 && primetime === true ) {
  alert("Let's carpool or do a ride share!");   
} else {
  alert("I think I'm gonna stay home today.");
}

Review Exercise

  • Create a variable named busRunning and ask the user if the bus is running today.
  • Create a second variable named passengerNum and ask the user how many passengers are currently on the bus.
  • Create a conditional statement that says if the bus is running AND the bus has less than or equal to 75 passengers, the program gives them an alert that says “You can take the bus!”
  • Otherwise, the user should get an alert that says “You will have to wait.”
Exercise Time Trello Logo

Review Exercise

Create a variable named userAge; set it equal to the answer your user types into a prompt when asked how old they are.

If the user is over 25 tell them that they can rent a car.

If not tell them that they cannot rent a car.

Exercise Time Trello Logo

Conditional Statements and Loops Overview

  • Understanding Control Flow
  • Conditional Statement Syntax
  • Equivalency Operators
  • Logical Operators
  • Loops Introduction
  • For Loops

Loops!

Introduction to Loops

Loops are a set of actions (e.g., instructions/code) that repeat:

  • for a designated number of times, OR
  • until a certain condition is met

Introduction to Loops

You can use loops to:

  • create a list of 100 random numbers,
  • display 20 photos downloaded from a photo sharing website like Flickr,
  • repeatedly display a prompt dialog until a visitor correctly enters an answer to a quiz question,
  • create a playlist of songs from select genres,
  • customize the formatting of a downloaded list of To Do items.

Can you think of a situation where you would use a loop?

Loops

There are many different ways to create loops in JavaScript (and other programming languages).

Roller coaster as a visual representation of a loop, an action that repeats until a condition is met

Loops

What’s the difference between a loop and a conditional statement?

IF music plays, I will do a dance. AND
WHILE music is playing, I will continue dancing.

Conditional Statements and Loops Overview

  • Understanding Control Flow
  • Conditional Statement Syntax
  • Equivalency Operators
  • Logical Operators
  • Loops Introduction
  • For Loops

For loops

Your new best friend :)

Intro to for loops

  • For loops are the most popular type of loop in JavaScript.
  • For loops are frequently used for actions that need to run a particular number of times.
  • For loops are also a common way to work with arrays, which are lists of data.
  • For loops frequently look through all of the items in an array one at a time.
  • Examples: arrays of images, tasks, links, items, etc.

For Loop Syntax, Part I

             
for (let i = 0; i < 10; i++){
  //....do something...
}

A for loop has a declaration of a variable that is a counter.

We give the counter a value.

The counter tells the loop where it should start running.

Example: let i = 0;

For Loop Syntax, Part II

             
for (let i = 0; i < 10; i++){
  //....do something...
}

A for loop also has a condition that evaluate to true.

The for loop only runs when the condition is true.

The for loop stops running when the condition is false.

Example: i < 10;

For Loop Syntax, Part III

             
for (let i = 0; i < 10; i++){
  //....do something...
}

A for loop also has a counter change.

The change occurs as the loop runs.

This change helps the loop stop.

Example: i++;

Counting from 0 to 10

             
// start from 0
// check if our count is 10 yet
// if not count it (add one)  
for (let i = 0; i <= 10 ; i++){
    console.log(i);
}

Count from 10 to 0


for (let i = 10; i >= 0 ; i--){
	console.log(i);
}

Quick challenge

Create a for loop that logs the numbers 4 to 156 to the console.

To log a value to the console use the console.log( ) method.

Looping through an array

  • You can use a loop to go through each item of an array.
  • Remember: arrays use zero indexes to count each element that is stored inside of them.
       
var favoriteColors = ["red", "blue", "purple", "yellow"];
for (let i = 0; i < favoriteColors.length ; i++){
    console.log("I really like the color: " + favoriteColors[i]);
}

Explain this code:

       
var fruitSnacks = ["dried cranberries", "fresh blueberries", "apple crisps", "plantain chips"];
for (let i = 0; i < fruitSnacks.length ; i++){
    console.log("I need to stock up on: " + fruitSnacks[i]);
}

The Recipe Card

Create an object to hold information on your favorite recipe.

Your object should have these properties:

  • title (a string)
  • servings (a number)
  • ingredients (an array of strings)

Then loop through each ingredient in the array to log to the console:

Recipe Card
Exercise Time Trello Logo

Remainder Operator

The remainder operator can help us find out what something is divisible by.

The remainder is a term used in division.

Examples: 4 divided by 2 has a remainder of 0.
4 divided by 3 has a remainder of 1.

Remainder Operator Syntax

       
10 % 2 === 0 //this is true
9 % 3 === 0 //this is true
10 % 3 === 1 //this is true
15 % 4 === 0 //this is false

Remember, the remainder operator tells us if there is a remainder after the number on the left has been divided into by the number on the right.

Remainder Exercise

Find all of the even numbers from 0-100 and add them to an array called “even”.

Find all numbers divisible by 8 in the array called "even" and add it to a different array called “myEights”.

Exercise Time Trello Logo

Favorite Foods Exercise

  • Create an array called favoriteFood and add 6 items to the array.
  • Create a function called printFoods that passes the argument of lists through it.
  • Within the function, create a for loop that writes to the document “My number [ ] favorite food is [ ]” for each item in the array.
  • Call the function with the favoriteFood array.
Exercise Time Trello Logo

The Reading List

Create an array of objects, where each object describes a book and has 3 properties: title (a string), author (a string), alreadyRead (a boolean to note if you've read it yet).

Iterate through the array of books. For each book, log the book title and its author like so: "The Hobbit by J.R.R. Tolkien".

Now use an if/else statement to change the output depending on whether you've read it yet or not. If you've read it, log a string: 'You already read "The Hobbit" by J.R.R. Tolkien'; if not, log a string: 'You still need to read "The Lord of the Rings" by J.R.R. Tolkien.'

Exercise Time Trello Logo

in pictures

Control Flow

This image visually depicts a for loop that has an if statement inside of its code block. When might we want to use that?

Song Exercise

Hint: Be mindful of infinite loops, which crash browsers!

  • Ask the user how many verses they want to hear.
  • Write code that console logs the "Bottles of Sprite on the wall" song:
  • 10 bottles of Sprite on the wall,
    10 bottles of Sprite!
    Take one down and pass it around,
    9 bottles of Sprite on the wall!

  • How would you fix "1 bottles of Sprite"?
  • How would you change "0" to "No more"?
Exercise Gif Trello Logo

The Movie Database

Reference this collection of movies.

Create a loop that checks the duration of each movie object and logs to the console the titles of the movies that are longer than 150 minutes.

Exercise Time Trello Logo

Intro to For In Loops

  • For in loops are another way to loop in JavaScript.
  • For in loops are only used with objects to commonly search for a particular key.

How do for in loops work?

                                   
for (let [key] in [object]) {
 	//...do something...
}

The object is the name of the object that we want to loop through.

Note the built-in stopping point for the for in loop: it will stop when there are no more keys in that object to loop through.

Objects Review

  • An object in JavaScript is a self-contained set of related values and functions.
  • It is a great way to keep data and functions about one item (or object) together.
  • An object literal is an object that is created directly in the language by wrapping all of its properties and methods in curly braces.
  • Objects contain key/value pairs.

Example of Object Literal

             
var superman = {
    name: "Superman",
    fakeName: "Clark Kent",
    height: 6.4,
    weight: 215,
    hero: true,
    allies: ["Superwoman", "Batman", "Wolverine"],
    fly: function() {
        return "Up, up, and away!";
    }
}
    

Adding Items to Objects

 
var coach = {
    favFood: ["cords","sticks", "penguins"],
    owner: {name:"Jessica", age: 32, city: "SF"}
};
coach.favFood.push("chicken");
console.log(coach.favFood);
coach.owner.hairColor = "bronze";
function hair() {
    console.log(coach.owner.hairColor);
}
hair();
    

For in loops with objects

We can loop through all of an object’s keys and values by using a for in loop, which is specific to objects.

We can create a variable “key” that is used to represent the name of each key in the superman object in the for in loop.

                                   
for (let key in superman) {
    console.log(key + “: ” + superman[key]); 
}
    

This will log to the console all of the data in our superman object.

Object Iterating Exercise

Given an object:

      
var acClass = { 
    lovely: "orange",
    hptrust: "red",
    drjules: "purple",
    sparkle: "yellow",
    infinite: "blue",
    missmorpheus: "silver",
    ubuspeaks: "green",
    taiyz: "pink"
}
    

Find all of the pink values and return an array of the names with pink value.

If/else statements in a for in loop

      
var summit = { 
    abbi: "phone",
    belle: "web",
    cadence: "phone or web",
    devon: "phone",
    elmo: "phone",
    fey: "web",
    gerardo: "phone or web",
    helena: "phone or web",
    ian: "web",
    jacques: "web",
    koriko: "phone or web",
    leslie: "web",
    millie: "phone or web",
    nigel: "web"
}

Find all summit attendees who have indicated "web" as their plan, and push each of their names into an array.

Conditional Statements and Loops Overview

  • Understanding Control Flow
  • Conditional Statement Syntax
  • Equivalency Operators
  • Logical Operators
  • Loops Introduction
  • For Loops

The End

Thanks for your attention. :)