Please read Chapter 4
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?
We need programs to take in and respond to user input.
1. Ways to see if the program is working under certain conditions
2. Ways to make our programs responsive to the user
A boolean can only have two values:
TRUE or FALSE;
YES or NO.
Programs love booleans because:
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.
Voting |
If a user is registered to vote, they can vote. |
---|---|
Weather | If it is pouring, I want to use an umbrella. |
Sorbet | If hot outside, I want a sorbet. |
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."
On the board or virtual chat,
write an example of control flow:
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 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. |
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 picture helps us understand a more complex
Control Flow.
Instead of just testing if a condition is true, we have:
The "else" statement is a program option if the main condition tested is "false". The else statement is the "catch-all."
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.
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.
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.
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.
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 ==
.
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!
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.
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 |
“javascript”===“JavaScript”
false
“3”===3
false
“lion” > “zebra”
false
“lion” !== “zebra”
true
1000 <= 1000
true
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!");
}
"Falsey Values": these will evaluate to false if they are in the conditional statement
var a;
if (a) {
alert("yay!")
} else {
alert("boooo!")
}
Will the code block run?
If so, which code block will run?
What if we needed a third option, a Door #3?
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.
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.
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?
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!
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!!!");
}
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");
}
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 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.");
}
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!");
}
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!");
}
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!");
}
var ships = 10;
var score = 0;
if ( ships === 0 || score === 0 ) {
console.log('Game over.');
} else {
console.log('Your score is zero.');
}
var x = 10;
var y = 20;
if ( x < 10 && y > 10 ) {
console.log('The condition passes.');
} else {
console.log('The condition fails.');
}
Pair up to think of some real-world situations where you would need:
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.
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.");
}
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.");
}
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.
Loops are a set of actions (e.g., instructions/code) that repeat:
You can use loops to:
Can you think of a situation where you would use a loop?
There are many different ways to create loops in JavaScript (and other programming languages).
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.
Your new best friend :)
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 (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 (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++;
// 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);
}
for (let i = 10; i >= 0 ; i--){
console.log(i);
}
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.
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]);
}
Create an object to hold information on your favorite recipe.
Your object should have these properties:
Then loop through each ingredient in the array to log to the console:
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.
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.
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”.
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.'
This image visually depicts a for loop that has an if statement inside of its code block. When might we want to use that?
Hint: Be mindful of infinite loops, which crash browsers!
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!
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.
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.
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!";
}
}
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();
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.
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.
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.
Thanks for your attention. :)