JS Cohort Class 4 Notes & Exercises - tinuola/gdi-classes Wiki

JS Cohort Class 4 Notes & Exercises

Great job with Class 4, everyone!

We had fun with conditionals, truthy and falsy values, and our first foray into loops.

It's amazing how much we've covered in two weeks! To help us finish strong in our last two classes, I've included notes (and exercises) below for topics to review that we couldn't cover in Class 4. We'll touch on them briefly in Class 5.

These sections are marked below with the :alarm_clock: icon.

In Class 5, we'll explore functions and meet our final data types: Arrays and Objects.

Do what you can with the review sections and take-home exercises, but most of all, enjoy the long weekend! 🎉 🎉 🎉

Thanks!

Check-in survey for Class 4 - https://forms.gle/rbxtYsca6kwFdJLbA

Conditionals

We use conditional statements to control the behavior of our application--to set or determine the conditions under which our code should run, or in what way it should be executed.

Article: Conditionals (MDN)

If Statements

The if statement - If a condition is true, then run the code.

// `if` statement syntax:

if (condition is true) {
  do something
} 

Example 1:

let catsSay = 'meow';

// `if` statement or `if` block
if(catsSay === 'meow') {
  console.log("I love to sleep all day!")
}

Example 2:

// Create a variable called "temperature" and assign a number value to it. 

let temperature = 30

// Write an if statement that tells you to put on a coat if the 
// temparature is below 50 degrees.

if ( temperature < 50 ){
  console.log('It\'s a cold day; better wear a coat.')
}

If/Else Statements

If/Else extends or builds on the basic If statement by taking into account what should happen if the original condition we're evaluating is NOT true.

// `If/else` statement syntax:

if (condition is true) {
  do a
} else {
  do b
}

Example 1:

let catsSay = 'meow';

if (catsSay === 'meow'){
  console.log("I love to sleep all day!")
} else {
  console.log("I must be a dog then.... Woof!")
}

Example 2:

// Extend the `if` statement for the temperature code: Add an `else` block 
// that tells you it's okay to skip wearing a coat if the temperature
// is not below 50 degrees

let temperature = 30

if ( temperature < 50 ){
  console.log('It\'s a cold day; better wear a coat.')
} else {
  console.log('Nice weather! A sweater should be okay.')
}

Ternary Operator

:alarm_clock: Due to tiime, we are not actively covering Ternary Operators in this series.

Some developers feel if/else statements take up too many lines; that conditionals can be written in a shorter or cleaner way. There's a special operator or syntax for doing this called the Ternary Operator.

Article: Ternary Operator (MDN)

Check out the syntax and an example below. Run the code and try it out.

// Ternary operator syntax:

// condition we are evaluating ? what to do if true : what to do if false

let temperature = 30
let whatToDoIfTrue = `It's a cold day; better wear a coat.`
let whatToDoIfFalse = `Nice weather! A sweater should be okay.`

temperature < 50 ? whatToDoIfTrue : whatToDoIfFalse

If/Else If/Else (aka Chaining Conditionals)

But what if we have more than two scenarios or conditions to evaluate?

A basic if/else statement can be extended by adding extra conditional statements (aka else if) that have their own block.

// if/else if/else statement syntax:

/*

if ( condition1 is true ) {

   do something

} else if ( condition2 is true ) {

  do something else

} else if ( condition3 is true ) {

  do another thing entirely

} 

...

} else {

  None of the above condition is true? Then do this
  and let's call it a day!

}

*/

Example 1:

let today = 'thursday';

if( today === 'monday' ){
  console.log( 'Here we go again....' )
} else if( today === 'tuesday' ){
  console.log( 'Are we done yet?' )
} else if( today === 'wednesday' || today === 'thursday' ){
  console.log( 'Getting a bit excited...' )
} else if( oday === 'friday' ){
  console.log( 'Freeeedommmm' )
} else {
  console.log( 'I love the weekends!' )
}

Example 2:

// Create a variable called `color`

// Write an if/else-if/statement for the following scenario

// If `color` is blue, yellow, or red, print:
// '`color` is a primary color.'

// If color is orange, purple or green, print:
// '`color` is a secondary color.'

// If `color` is black or white, print:
// '`color` is technically not a color; it's considered a 'Shade'.'

// If `color` is any other color, print:
// 'I need to look up what type of color `color` is.'


let color = 'tomato'

if( color === 'blue' || color === 'yellow' || color === 'red'){
  console.log(`${color} is a primary color.`)
} else if( color === 'orange' || color === 'purple' || color === 'green'){
  console.log(`${color} is a secondary color.`)
} else if( color === 'black' || color === 'white'){
  console.log(`${color} is technically not a color; it's actually considered a 'Shade'.`)
} else {
  console.log(`I need to look up what type of color ${color} is.`)
}

Switch Statements

:alarm_clock: Due to time, we are not actively covering Switch Statements in this series.

As you can see, chained conditionals can get long and confusing pretty quickly. Similar to the Ternary Operator, there's a cleaner way to write them using what's called a Switch Statement.

Article: Switch Statement (MDN)

Check out the syntax and an example below. Run the code and try it out.

// Switch statement syntax:

/*

switch (expression) {
  case value1:
    //do this if the expression (condition) matches value1
    break;
  case value2:
    //do this if the expression (condition) matches value2
    break;
  case value3:
    //do this if the expression (condition) matches value3
    break;
  ...
  default:
    //do this when nothing matches
  break;
}

*/

let today = 'thursday';

switch (today){
  case 'monday':
    console.log( 'Here we go again....' )
    break;
  case 'tuesday':
    console.log( 'Are we done yet?' )
    break;
  case 'wednesday':
  case 'thursday':
    console.log( 'Getting a bit excited...' )
    break;
  case 'friday':
    console.log( 'Freeeedommmm' )
    break;
  default:
    console.log( 'I love the weekends!' )
}

Truthy and Falsy Values

All variables or data in JS have a default Boolean (true or false) value. They can be considered either truthy or falsy.

Falsy Values:

Article: Falsy (MDN)

false // The actual Boolean data type value

0

-0

'', "", `` // Empty strings are falsy

null

undefined

NaN // Stands for 'Not a Number'

Truthy Values:

Article: Truthy (MDN)

true // The actual Boolean data type value

4 // All numbers are truthy except 0 and -0

'hello' // All strings are truthy except empty strings

'0' // 0 as a string data type is truthy

'false' // When written as a string data type false is truthy

Infinity

[] // An empty array is truthy

{} // An empty object is truthy

What do these expressions or code snippets evaluate to? Take a guess, then run them in the console to check your answers.

Boolean('Jackie')

if('Jackie'){
  console.log(true);
}

Boolean(null)

if(!null){
  console.log(true)
} else {
  console.log(false)
}

Boolean(0)

if(0){
  console.log('JavaScript is weird sometimes')
}

Loops

In addition to making decisions about when to do certain things, the other common behavior of many programs or applications is to repeat tasks. They loop or iterate over a task. JavaScript has multiple ways of looping.

For Loops

A for loop is typically the first type of loop that we learn about in JavaScript.

A for loop executes a given code (or task) a set number of times under a specific condition.

// `for` loop syntax:

for (statement 1; statement 2; statement 3) {
  // code to be repeated
}

// statement 1 starts or initializes the loop
// statement 2 is the condition that determines if/when the loop should run
// statement 3 counts the looping cycle

Let's turn the above pseudo-code into code and break it down!

for ( let i = 1; i < 5; i++  ){
  console.log(i)
}

// let i = 1 ====> Declare and initialize a variable i that starts the loop.

// i < 5 ====> The loop is only going to run as long as i is less than 5.

// i++ =====> Every time the loop runs, increase the value of i by 1

// console.log(i) =====> This is the code to run each cycle in the loop. 
// It will print the value of i (which increases by 1 each loop).

Loops can run conditionals!

Review the code below; try to understand what it's doing, and then run the code to check your assumption.

Thanks JulieD and Nada, for the question/scenario!

for(let num = 0; num < 20; num++){

  if(num % 5 === 0 ){
    console.log('Lauren')
  } else {
    console.log(num)
  }

}

Note 1: The starting variable of a for loop can be named or labeled in any way as long as it matches variable naming convention. It can also start at any integer value.

Note 2: The counter can also be incremented in any way we choose. You're not limited to counting up or down by 1.

See the example below and run the code!

for ( let age = 15; age < 100; age +=10 ){
  console.log(age);
}

Note 3: A for loop is one scenario in JavaScript where semicolons MUST be included.

Note 4: Loops can count down! Change the starting value and conditions, and use the -- decrementer operator.

// Counting up...

for ( let x = 1; x <= 10; x++ ){
  console.log(`Number ${x}`)
}

// Counting down...

for ( let x = 0; x >= 0; x-- ){
  console.log(`Number ${x}`)
}

Note 5: Loops are finicky! When written incorrectly or inefficiently, a loop will crash/freeze your browser window or application.

Usually this happens if/when we write a loop in which the condition is always true. This means the loop will never stop running.

// This loop will run indefinitely because `num` will ALWAYS 'not be equal to super'.

for(let num = 0; num !== 'super'; num++){
   console.log('Lauren ' + num)
}

// Wanna try it? 😈 😈 😈

// Open up an incognito browser window.
// Type or paste the code into the console.
// Run the code.
// Then try to run a random console statement: console.log('hey')
// What happens?...
// Congrats! You've created your first infinite loop.
// It happens to everyone!

While Loops

:alarm_clock: We'll cover while loops briefly in Class 5.

Similar to a for loop, a while loop also checks that a specific condition must be met to run or execute code. Its syntax is a bit different from a for loop's, but the concept is still the same.

// `while` loop syntax:

// Set up a starting condition, then the loop:
while (condition is true) {
  // code block to be executed
  // counter
}

Let's turn this into code:

let x = 1

while (x <= 10){
  console.log(x);
  x++;
}

// While x is less than or equal to 10, console the value of x, and repeat until we get to 10

Similar to the for loop, the while loop also counts down:

// Remember to update the conditions and counter!

let x = 10

while (x >= 0){
  console.log(x);
  x--;
}

A while Loop example:

let countName = 1;

while(countName <= 50){
  document.write('Tinuuuuuuuu<br>');
  countName++;
}

For or While?

:alarm_clock: You might be wondering: "When do I use a for loop over a while loop?"

Technically, they do the same thing or can be used interchangably.

A subtle difference is that a for loop will run for a given or set number of times. A while loop can also do this AND can be used when we're more interested in a condition being met (rather than the number of times to run the loop).

Article: When do I use a for loop and when do I use a while loop (Khan Academy)

Article: The Difference Between For Loops and While Loops in JavaScript

Breaking a Loop

:alarm_clock: Sometimes you may want to exit your loop early. You can do this with what's called a break statement.

Review the code expressions below and try to determine what they're both meant to do. Then run them in your console.

// Breaking a `for` loop:

for(let age = 2; age <= 12; age++){
  if(age === 5){
    break;
  }
  console.log(age)
}

// Breaking a `while` loop:

let tip = 5

while (tip <= 50){
  console.log(`The most I'll tip is ${tip}%`)
  tip+=5;
  if(tip === 30){
    break;
  }
}

Exercises

Conditionals

If / Else statement

let teacher = 'Tinu'
let job = 'Developer'

// Create an if/else statement that satisfies or checks for the following:

// That IF Tinu is the teacher AND that her job is a developer 
// THEN display ('This is the right class) ELSE display 
// ('This must be the wrong class')

// Hint: You'll need to use logical operators.

If / Else if / Else statement


// Create a variable called "myDailyRun" and assign it a number value.

// Create an if/else-if/else chain for the following scenarios:

// myDailyRun is less than 5, display 'I think I'll stick with 5ks for now'

// myDailyRun is between 6 and 15, display 'I'm ready to run a 10k'

// myDailyRun is between 16 and 25, display 'I can definitely do a half-marathon'

// myDailyRun is greater than 25, display 'Marathon time!'

// Tip: Create the 'skeleton' first and then insert the conditions...

Ternary Operator and Switch Statement

:alarm_clock: We are not actively covering Ternary Operators and Switch Statements in this series, but you can still try them. In fact, I encourage you to!

Study the patterns/example code in the class notes and then rewrite the two conditional exercises above as a ternary operator and a switch statement respectively.

More practice? Turn the below exercises from the class notes into a ternary operator and a switch statement respectively.

// Rewrite or 'refactor' this code using the Ternary Operator:

let catsSay = 'meow';

if (catsSay === 'meow'){
  console.log("I love to sleep all day!")
} else {
  console.log("I must be a dog then.... Woof!")
}

// Rewrite or 'refactor' this code using a Switch Statement:

let color = 'tomato'

if( color === 'blue' || color === 'yellow' || color === 'red'){
  console.log(`${color} is a primary color.`)
} else if( color === 'orange' || color === 'purple' || color === 'green'){
  console.log(`${color} is a secondary color.`)
} else if( color === 'black' || color === 'white'){
  console.log(`${color} is technically not a color; it's actually considered a 'Shade'.`)
} else {
  console.log(`I need to look up what type of color ${color} is.`)
}

Loops

// Create a `for` loop printing your name 20 times
// Create a `while` loop printing your name 20 times
// Change the counter in the `for` loop below to increase by 2
// Hint: Use a compound assignment operator

for (let j = 0; j <=20; ???) {
// console.log the value of j
// Result: Should print out only even numbers...
}
// Create a `while` loop that counts down to zero and
// runs the following output: document.write(`I hate doing dishes<br>`)

// Starting condition
let dirtyDishes = 10

// while loop....
// Write a `for` loop that loops through the numbers 1 to 20 
// and prints the results according to the following conditions:

// if the number is even, print the word "even"

// if the number is odd, print the word "odd"

// Extra challenge! If the number is divisible by 3 AND 5, print your name!
let sum = 0

for (let i = 1; i <= 10; i++) {
  // console.log the value of sum as it's updated or increasing by i
}

Solutions