This workshop is important because:
"Control flow" refers to the way our computers move through a program's code. Understanding control flow allows us to trace the flow of a program based on its code. This skill is essential for programming in every language and paradigm. In particular, conditionals and loops are fundamental to understanding modern programming languages.
After this workshop, developers will be able to:
- Predict the output of boolean expressions, including "truthy" and "falsey" values.
- Write conditional statements based on descriptions of behavior.
- Compare & contrast
for
andwhile
loops. - Write loops based on descriptions of behavior.
- Identify "blocks" in JavaScript code.
Before this workshop, developers should already be able to:
- Create and change variables of many types in the Chrome developer tools.
- Access and change values within objects and arrays.
Think of a decision you make often, like what to eat for lunch, whether to wear a jacket, or how much time you will set aside to travel to an event from your house. Using variables and conditionals, pseudocode your decision-making process. Here's an example:
// do I bring an umbrella?
// variables:
// currentlyRaining (boolean)
// chanceOfRain (number, for percent chance of rain)
// me (object, represents me)
if (currentlyRaining || chanceOfRain > 70) {
// bring umbrella!
me.hasUmbrella = true;
} else {
me.hasUmbrella = false;
}
In boolean logic, every value is either true
or false
.
typeof(true) // boolean
typeof(false) // boolean
JavaScript also treats every value as "truthy" or "falsey".
To work within this system, we have to memorize which values are "falsey." It can take practice to quickly predict results, but developers can use this truthy/falsey system to write shorter code for conditional expressions.
To check whether some value is truthy or falsey, try the following structure in your JavaScript console:
let myValue = "fishing";
if(myValue){
console.log(myValue, " is truthy!");
} else {
console.log(myValue, " is falsey!");
}
An "operator" is represents a simple operation that can be done on an input to give some output, like +
and -
from math!
These operators give boolean outputs, but in JavaScript their inputs could be anything.
English: "and"
JavaScript: &&
Example: a && b
Spoken: "A and B"
Rule: true
when both sides are truthy
English: "or"
JavaScript: ||
Example: a || b
Spoken: "A or B"
Rule: true
when at least one side is truthy
English: "not"
JavaScript: !
Example: !b
Spoken: "not B"
Rule: reverses value (true
when b
is falsey)
English: "not not"
JavaScript: !!
Example: !!b
Spoken: "not not B"
Rule: true
when b
is truthy
The
!
operator is sometimes pronounced 'bang!'.
These operators give boolean outputs, but in JavaScript their inputs could be anything.
strict equality | loose equality | not strictly equal | not loosely equal | greater than | less than | greater than or equal to | less than or equal to |
---|---|---|---|---|---|---|---|
=== |
== |
!== |
!= |
> |
< |
>= |
<= |
Strict equality checks type and value, while loose equality only compares value.
- What is the outcome of the following expressions?
true || false
false && false
true && false
(false || true) && true
false && ((true || false) && (false || true))
answers
```js true || false // true false && false // false true && false // false (false || true) && true // true false && ((true || false) && (false || true)) // false ``` Note that JavaScript is lazy when it can quit evaluating a boolean expression early. For example, in the last expression above, you can tell from just the first `false &&` that the whole expression will be false.- Which of the following are falsey?
"abc"
""
1
-0
Math.PI
NaN
Array
[]
Object
{}
null
undefined
answers
truthy: `-0`, `""`, `NaN`, `null`, `undefined`- What is the outcome of the following expressions?
1 && 6
0 || "hi"
["a","b","c"] || "123"
false || null
answers
```js 1 && 6 // 6 0 || "hi" // "hi" ["a","b","c"] || "123" // ["a","b","c"] false || null // null ```The boolean expression inside an if
's parentheses will always be evaluated as truthy or falsey to determine what will happen next.
A diehard Giants fan might have the following rules for baseball games:
if (giantsPlaying) {
// get tickets to the game
}
if (!giantsPlaying) {
// don't watch the game
}
We can rephrase this more succinctly using if
and else
.
if (giantsPlaying) {
// get tickets to the game
} else {
// don't watch the game
}
Getting tickets to all Giants games would be expensive! Maybe the Giants fan only wants to watch games that are in San Francisco.
if (giantsPlaying && gameInSF){
// get tickets to the game
} else {
// don't watch the game
}
If the Giant fan wants to watch games outside San Francisco, watching on TV might be an easier option.
if (giantsPlaying && gameInSF){
// get tickets to the game
} else if (giantsPlaying){
// watch on tv
} else {
// don't watch the game
}
Here's a strategy someone might use for choosing what to drink. Assume there's already a person
variable saved.
let drink;
if (person.sleepy) {
if (before5pm) {
drink = "coffee";
} else {
drink = "black tea";
}
} else {
if (person.isHungry){
drink = "smoothie";
} else {
drink = "water";
}
}
A switch
statement checks the value of one variable or expression to determine which of many "cases" to jump to. Here's code for a vending machine with a different price for each row:
switch (row){
case 1:
price = 0.25;
break;
case 2:
price = 0.50;
break;
case 3:
price = 0.75;
break;
case 4:
price = 1.00;
break;
default: // the rest of the products (rows 5-7)
price = 1.25;
}
Any switch
statement can be written as a series of if
, else if
, and/or else
. For WDI, we suggest avoiding switch
.
Loose Control Flow (watch out for edge cases!)
let username = `${firstInitial}${lastName}`;
if ( username ) {
// submit signup form
}
// code above does the same as:
if ( username.length > 0) {
// submit signup form
}
Ternary operator
var username = lastName ? `${firstName}${lastName}` : firstName;
// same as
var username;
if ( lastName ) {
username = `${firstName}${lastName}`;
} else {
username = firstName;
}
Conditional assignment: ||
to set to a default value
var bestCity = yourCity || "San Francisco";
// same as
var bestCity = "San Francisco";
if ( yourCity ) {
bestCity = yourCity;
}
Remember, variables created with JavaScript ES6's let
and const
reserved words have "block scope," meaning they only exist INSIDE the "block" where they were created.
So what is a block?
A block is the portion of an if
, else
, for
, switch
, or similar statement that is between {
and }
. Functions also have their own blocks.
-
In the example below, which line(s) are inside the
if
statement's block?1 2 if ( degrees === 90 ) { 3 4 console.log('right angle'); 5 } 6
-
In the ES6 example below, on what line(s) is the
angle
variable in scope?1 2 if ( degrees === 90 ) { 3 let angle = 'right'; 4 console.log(`${angle} angle`); 5 } 6
-
In the ES6 or ES5 example below, on what lines is the
angle
variable in scope?1 2 if ( degrees === 90 ) { 3 var angle = 'right'; 4 console.log(angle + ' angle'); 5 } 6
Whiteboard with a partner:
Jimmy loves roller coasters, but there are a bunch of rules (ugh!) for riding:
For starters, it costs 5 tokens. Here's how we might code that:
// assume we'll have a tokens variable
// storing the number of tokens
if ( tokens >= 5 ) {
console.log("Step right up!");
} else {
console.log("Sorry, you can't ride")
}
Pseudocode or edit the code above to check the following requirements. You can assume there are variables stored for tokens
, height
, age
, hasAdult
, bossLooking
, and hasPass
.
- Add a requirement that riders must be at least 4ft tall.
answer
if (tokens >= 5 && height >= 4) {
console.log("Step right up!");
} else {
console.log("Sorry, you can't ride.");
}
- Add a requirement that riders must be at least 12 years old.
answer
if (tokens >= 5 && height >= 4 && age >=12) {
console.log("Step right up!");
} else {
console.log("Sorry, you can't ride.");
}
- Replace the previous rule with this new rule: now riders under 12 can participate if they have an adult with them.
answer
if (tokens >= 5 && height >= 4 ) {
if (age >= 12 || hasAdult){
console.log("Step right up!");
} else {
console.log("Sorry, you can't ride.");
}
} else {
console.log("Sorry, you can't ride.");
}
- (If the boss isn't looking, you can go on in!)
answer
if (!bossLooking){
console.log("Step right up!");
} else {
if ( tokens >= 5 && height >= 4 ) {
if (age >= 12 || hasAdult){
console.log("Step right up!");
} else {
console.log("Sorry, you can't ride.");
}
} else {
console.log("Sorry, you can't ride.");
}
}
- Riders with a park pass get in free.
answer
if (!bossLooking){
console.log("Step right up!");
} else {
if ( (tokens >= 5 || hasPass) && height >= 4 ) {
if (age >= 12 || hasAdult){
console.log("Step right up!");
} else {
console.log("Sorry, you can't ride.");
}
} else {
console.log("Sorry, you can't ride.");
}
}
Whenever we want to repeat something in code, we use a loop. We can think of every loop as three parts: initialization (setup), continue condition, and update expression.
While pizza is available, take pizza!
In while loops, the initial setup happens before the loop. The continue condition goes inside the while
parentheses. The updates happen inside the loop.
var batteryPercent = 100; // setup: initial state of battery
while (batteryPercent > 10) { // continue condition: enough battery
useDevice();
batteryPercent = batteryPercent - 5; // update: reduce time left
}
For loops allow the setup, continue condition, and update expression to live inside the for
loop parentheses.
for (var count = 1; count <= 3; count++){
console.log(count);
}
console.log("Go Team!");
For loops only really need a continue condition (or the loop will never end!). We can do setup before the loop, and we can do updating inside the loop. In this way, a for loop can look a lot like a while loop.
var minutesBeforeWork = 540;
for( ; minutesBeforeWork > 30; ) {
minutesBeforeWork = minutesBeforeWork - 5;
}
For loops for arrays usually use a counter variable to move through the indices of the array.
var friends = ["Bali", "Nat", "Kelly"]
for (var i = 0; i < friends.length; i++) {
console.log(friends[i] + " is a nice person");
}
In ES6, for ... of
loops are used to loop through arrays.
var friends = ["Bali", "Nat", "Kelly"]
for (let friend of friends) {
console.log(`${friend} is a nice person`);
}
We'll see how to use special iterator methods to move through arrays sequentially. Iterator methods are wonderful for that. For loops in JavaScript are much more flexible than iterator methods, though, so it's important to get a handle on them.
The reserved word break
will break us out of a loop immediately.
for (var i = 0; i < 10; i+=2) {
console.log(i);
break;
}
var j=0;
while (j < 10) {
console.log(j);
break;
j += 2;
}
Use a for
or while
loop to console log a shuttle launch countdown: "T minus 10", then "9", "8", "7", "6", "5", "4", "3", "2", "1", "0", "Liftoff!".
for loop answer
console.log("T minus 10");
for (var i=9; i>=0; i--){
console.log(i); // can log i.toString() to convert
}
console.log("Liftoff!");
while loop answer
console.log("T minus 10");
i = 9;
while (i>=0){
console.log(i); // can use i.toString() to convert
i--;
}
console.log("Liftoff!");
The most important things to practice right now are:
- predicting the output of boolean expressions.
- working with more complex, nested conditionals and/or loops.
- remembering the three-part structure of loops and the syntax for each kind of loop.