Conditionals & Loops

Objectives

  • Use if/else conditionals to control program flow based on Boolean (true or false) tests.
  • Use Boolean logic (!, &&, ||) to combine and manipulate conditional tests.
  • Use switch/case conditionals to control program flow based on matching explicit values.
  • Differentiate among true, false, 'truth-y', and 'false-y'.
  • Review loop iteration using for and forEach, and introduce while and do/while loops.

Review

  • Describe the concept of a "data type" and how it relates to variables.
  • Declare, assign to, and manipulate data stored in a variable.
  • Create arrays and access values in them.
  • Iterate over and manipulate values in an array.

Conditionals allow us to check a condition, and respond to the answer of that condition

Comparison Operators

Comparisons in JavaScript can be made using <, >, <= and >=.

"A" > "a"
//=> false

"b" > "a"
//=> true

12 > "12"
//=> false

12 >= "12"
//=> true

General

Equality

True

Equality

Equality Operators

"dog" == "dog";
//=> true

1 == true;
//=> true
1 === true;
//=> false

true === true;
//=> true

"hello" === "hello"
//=> true

Remember the difference between equality and assignment

!= and !==

There are also != and !== operators, which are the negative versions of == and ===. 

Negation

Truthy and Falsey

Does the value value coerces to true when evaluated in a boolean context.

What is Truthy & Falsy

function logTruthiness (val) {
    if (val) {
        console.log("Truthy!");
    } else {
        console.log("Falsy.");
    }
}

Truthy

// Outputs: "Truthy!"
logTruthiness(true);

// Outputs: "Truthy!"
logTruthiness({});

// Outputs: "Truthy!"
logTruthiness([]);

// Outputs: "Truthy!"
logTruthiness("some string");

// Outputs: "Truthy!"
logTruthiness(3.14);

// Outputs: "Truthy!"
logTruthiness(new Date());

Falsy

// Outputs: "Falsy."
logTruthiness(false);

// Outputs: "Falsy."
logTruthiness(null);

// Outputs: "Falsy."
logTruthiness(undefined);

// Outputs: "Falsy."
logTruthiness(NaN);

// Outputs: "Falsy."
logTruthiness(0);

// Outputs: "Falsy."
logTruthiness("");

Use Negation!

!!1
//=> true

!!0
//=> false

!!-1
//=> true

!![]
//=> true

!!{}
//=> true

!!null
//=> false

!!""
//=> false

Boolean and Logical Operators

Boolean Operators

  • AND, denoted "&&"
  • OR, denoted "||"
  • NOT, denoted "!"
true && true
//=> true

true && false
//=> false

false && false
//=> false

true || false
//=> true

false || true
//=> true

false || false
//=> false

!(true)
//=> false

Conditional Statements

If Statement

if (expr) { code }

if (1 > 0) {
  console.log("hi");
}
//=> hi

If/Else Statement

if (expr) { code } else { other code }

if (0 > 1) {
  console.log("hi");
} else {
  console.log("bye");
}
//=> bye

If/Else Statement

var name = "kittens";
if (name === "puppies") {
  name += "!";
} else if (name === "kittens") {
  name += "!!";
} else {
  name = "!" + name;
}
name === "kittens!!"
//=> true

Make sure to use EQUALITY not ASSIGNMENT in your If/Else Statement

// BAD
if (x = 3) {
    console.log("boo");
}

// GOOD
if (x === 3) {
    console.log("boo");
}

Ternary Operators

var age = 12;
//=> undefined

var allowed = (age > 18) ? "yes" : "no";
//=> undefined

allowed
//=> "no"

Independent Practice

Create a function that prints out the following statements based on the age input

  • If you are under 16, you cannot do much outside of going to school
  • If you are 16 or older, you can drive
  • If you 18 or older, you can vote
  • If you are 21 or older, you can drink alcohol
  • If you are 25 or older, you can rent a car
  • If you are 35 or older, you can run for president
  • If you are 62 or older, you collect social security benefits
function whatCanIDo(age){
    if (age < 16) {
      console.log('You can go to school!')
    } else if (age >= 16 && age < 18) {
      console.log('You can drive!');
    } else if (age >= 18 && age < 21) {
      console.log('You can vote!');
    } else if (age >= 21 && age < 25) {
      console.log('You can drink alcohol!');
    } else if (age >= 25 && age < 35) {
      console.log('You can rent a car!');
    } else if (age >= 35 && age < 62) {
      console.log('You can run for president!');
    } else if (age >= 62) {
      console.log('You can collect social security!');
    } else {
      console.log('Please enter a correct age value');
    }
}

Switch Statements

var food = "apple";

switch(food) {
  case 'pear':
    console.log("I like pears");
    break;
  case 'apple':
    console.log("I like apples");
    break;
  default:
    console.log("No favorite");
}
//=> I like apples

Let's Make a switch Statement

Create an if/else statement that returns a string, such as "Awesome Job" if the user gets a grade of “A” or "Bad Job" if they get an "F." Console.log a string for each letter grade.

Solution with If/Else

var grade = 'C';

if (grade === 'A') {
  console.log('Awesome job');
} else if (grade === 'B') {
  console.log('Good job');
} else if (grade === 'C') {
  console.log('Okay job');
} else if (grade === 'D') {
  console.log('Not so good job');
} else if (grade === 'F') {
  console.log('Bad job');
} else {
  console.log('Unexpected grade value entered');
}

Flip to a Switch!!

Solution with Switch 

var grade = 'C';

switch (grade) {
  case 'A':
    console.log('Awesome job');
    break;
  case 'B':
    console.log('Good job');
    break;
  case 'C':
    console.log('Okay job');
    break;
  case 'D':
    console.log('Not so good job');
    break;
  case 'F':
    console.log('Bad job');
    break;
  default:
    console.log('Unexpected grade value entered');
}

"break" in switch statements

var grade = 'C';

switch (grade) {
  case 'A':
  case 'B':
  case 'C':
    console.log('You passed!')
    break
  case 'D':
  case 'F':
    console.log('You failed')
    break
  default:
    console.log('Unexpected grade value entered')
}

=> You passed!

While and Do-While

"While" is a loop statement that will run while a condition is true.

while (true) {
  // an infinite loop!
}


// Try this in your browser! 
// What do you think will happen?
var input = 0;
do {
  console.log(input++);
} while (input < 10);
var result = "";
var i = 0;

do {
  i = i + 1;
  result = result + i;
} while (i < 5);

console.log(result);
// expected result: "12345"

Iteration

"for" loop

var a = [1, 2, 3, 4, 5];
for (var i = 0; i < a.length; i++) {
  console.log(i);
}

"forEach()" loop

["dog", "cat", "hen"].forEach(function(currentValue, index, array) {
   console.log("I want a ", currentValue);
   console.log(array[index]);
});

Fizz Buzz

Construct a for loop that iterates through, and console.log()'s out, numbers 1 - 100:

Add an if/else statement that logs the string "fizz" if the value being iterated over is divisible by 3; otherwise, log out the value:

Add an else if clause that logs the string "buzz" if the value being iterated over is divisible by 5:

Add an else if clause that logs the string "buzz" if the value being iterated over is divisible by 5

Review

  • Be able to explain if/else and switch statements as well as use cases.
  • Differentiate between true, false, 'truthy', and 'falsey'.

Homework

Assignment 1: 99 Bottles of Beer

  • Write a script that prints the lyrics to "99 Bottles of Beer on the Wall" in the terminal. Make sure your program can handle both singular and plural cases (i.e. both "100 bottles of beer" and "1 bottle of beer").

Assignment 2: Random Address Generator

  • Write a script that can generate random addresses
  • Each time you run the script, it should print a new randomly-generated address to the terminal. For example:
  • node random-address.js
  • => 34578 Dolphin Street, Wonka NY, 44506
Made with Slides.com