Back

Activity 2.3 Branching with If/Else

divider

Introduction

Activity 2.3

Branching with If/Else

Topics

  • Mutually Exclusive Conditions
  • Branching with else if and else statements

Mutually Exclusive Conditions

The last activity introduced us to the idea of controlling the flow of an application with if statements.

Each program had multiple if statements that execute if their conditions were true.

But what if you only want to execute one block of code out of a set of possibilities?

Mutually Exclusive Conditions

This code may output multiple letter grades.

let grade = 95;
// Curly braces omitted for brevity
if (grade >= 90)
console.log("A");
if (grade >= 80)
console.log("B");
if (grade >= 70)
console.log("C");
if (grade >= 60)
console.log("D");
if (grade < 60)
console.log("F");

Mutually Exclusive Conditions

A grade of 95 would outout A, B, C, and D.

let grade = 95;
// Curly braces omitted for brevity
if (grade >= 90)
console.log("A");
if (grade >= 80)
console.log("B");
if (grade >= 70)
console.log("C");
if (grade >= 60)
console.log("D");
if (grade < 60)
console.log("F");

Mutually Exclusive Conditions

Mutually exclusive conditions ensure only one selection is chosen from a list of possibilities.

These types of statements are also known as branching statements.

Branching with else if and else Statements

The if, else if, else structure is a way to control the flow of a program by executing exactly one block of code from a series of options.

It's used to handle mutually exclusive conditions, where only one outcome is possible.

Components of an if, else if, else structure

  • if: The first condition in the chain that is checked. You must always start with an if statement.
  • else if: A condition that is only checked if all preceding if or else if statements were false. You can have multiple else if statements.
  • else: An optional "catch-all" or "fallback" block that runs only if all preceding if and else if conditions were false.

else Statements

Simple Pass/Fail Checker
let grade = parseInt(prompt("Enter grade:"));
if (grade > 60) {
console.log("Pass!");
}
else {
console.log("Fail!");
}
Enter grade: 45 [Enter]
Fail!
Enter grade: 78 [Enter]
Pass!

else Statements

Simple Login Prompt
let password = prompt("Enter password:");
let secret = "secret123";
if (password == secret) {
console.log("Access granted.");
}
else {
console.log("Access denied.");
}
Enter password: secret123 [Enter]
Access granted.
Enter password: secretpassword [Enter]
Access denied.

else if Statements

Corrected Letter Grade Program
let grade = parseInt(prompt("Enter grade:"));
// braces ommitted for brevity
if (grade >= 90)
console.log("A");
else if (grade >= 80)
console.log("B");
else if (grade >= 70)
console.log("C");
else if (grade >= 60)
console.log("D");
else
console.log("F");
Enter grade: 86 [Enter]
B

else Statements

Corrected Letter Grade Program
let grade = parseInt(prompt("Enter grade:"));
// braces ommitted for brevity
if (grade >= 90)
console.log("A");
else if (grade >= 80)
console.log("B");
else if (grade >= 70)
console.log("C");
else if (grade >= 60)
console.log("D");
else
console.log("F");
Enter grade: 49 [Enter]
F

Key Terms

Branching Statements
Statements that allow a program to follow one of several possible paths of execution based on a condition. The if, else if, else structure is a type of branching statement.
else if
A keyword that introduces an additional condition. The else if block is only checked and executed if the preceding if or else if statements were all false.

Key Terms

else
A keyword that introduces a final, optional block of code. The else block acts as a "catch-all" and will execute if all preceding if and else if conditions were false.

'F' → Fullscreen

Objectives

  • icon Using if, else if, and else statements to create mutually exclusive conditions.
divider

Activity Tasks

  • icon Create a new project named 2-3-branching-if-else.js.
  • icon Complete each task individually.

Task 1: Chinese Zodiac Calendar

  • icon Each birth year maps to one of twelve zodiac animals in a repeating cycle. To find the corresponding animal, use the formula birthYear % 12, which gives you a remainder between 0 and 11.
  • icon Tip: Once you've written you first else if copy and paste it to speed things up, just tweak the values as needed.
2-3-branching-if-else.js
console.log("--- Chinese Zodiac Calendar ---");
let birthYear = parseInt(prompt("Enter your birth year: "));
let zodiacNumber = birthYear % 12;
let zodiacAnimal; // Assign animal based on birth year
if (zodiacNumber == 0) {
zodiacAnimal = "monkey";
}
else if (zodiacNumber == 1) {
zodiacAnimal = "rooster";
}
else if (zodiacNumber == 2) {
zodiacAnimal = "dog";
}
else if (zodiacNumber == 3) {
zodiacAnimal = "pig";
}
else if (zodiacNumber == 4) {
zodiacAnimal = "rat";
}
else if (zodiacNumber == 5) {
zodiacAnimal = "ox";
}
else if (zodiacNumber == 6) {
zodiacAnimal = "tiger";
}
else if (zodiacNumber == 7) {
zodiacAnimal = "rabbit";
}
else if (zodiacNumber == 8) {
zodiacAnimal = "dragon";
}
else if (zodiacNumber == 9) {
zodiacAnimal = "snake";
}
else if (zodiacNumber == 10) {
zodiacAnimal = "horse";
}
else if (zodiacNumber == 11) {
zodiacAnimal = "sheep";
}
else {
// Exit if input was invalid (NaN)
console.log("Something went wrong. Exiting.");
Deno.exit();
}
console.log(`\nBirth year: ${birthYear} - You are the year of the...${zodiacAnimal}.\n`);
alert("Press enter to continue...");
//

Task 2: Simple Lottery Game

2-3-branching-if-else.js
console.log("--- Chinese Zodiac Calendar ---");
let birthYear = parseInt(prompt("Enter your birth year: "));
let zodiacNumber = birthYear % 12;
let zodiacAnimal; // Assign animal based on birth year
if (zodiacNumber == 0) {
zodiacAnimal = "monkey";
}
else if (zodiacNumber == 1) {
zodiacAnimal = "rooster";
}
else if (zodiacNumber == 2) {
zodiacAnimal = "dog";
}
else if (zodiacNumber == 3) {
zodiacAnimal = "pig";
}
else if (zodiacNumber == 4) {
zodiacAnimal = "rat";
}
else if (zodiacNumber == 5) {
zodiacAnimal = "ox";
}
else if (zodiacNumber == 6) {
zodiacAnimal = "tiger";
}
else if (zodiacNumber == 7) {
zodiacAnimal = "rabbit";
}
else if (zodiacNumber == 8) {
zodiacAnimal = "dragon";
}
else if (zodiacNumber == 9) {
zodiacAnimal = "snake";
}
else if (zodiacNumber == 10) {
zodiacAnimal = "horse";
}
else if (zodiacNumber == 11) {
zodiacAnimal = "sheep";
}
else {
// Exit if input was invalid (NaN)
console.log("Something went wrong. Exiting.");
Deno.exit();
}
console.log(`\nBirth year: ${birthYear} - You are the year of the...${zodiacAnimal}.\n`);
alert("Press enter to continue...");
// -----------------------------------------------------------------------------
console.log("\n--- Lottery Game ---\n");
console.log("Rules: Pick two lottery numbers ranging from 0 to 9");
console.log("Match two numbers and win BIG!");
console.log("Match one number in order and win SMALL!\n");
let lottoNum1 = parseInt(prompt("Enter your 1st lottery number (0 to 9): "));
let lottoNum2 = parseInt(prompt("Enter your 2nd lottery number (0 to 9): "));
let winningNum1 = Math.floor(Math.random() * 10);
let winningNum2 = Math.floor(Math.random() * 10);
// Exit the program if either lotto number is out of range
if (lottoNum1 < 0 || lottoNum1 > 9 || lottoNum2 < 0 || lottoNum2 > 9) {
console.log("Error: Your lotto numbers are invalid. Exiting");
Deno.exit();
}
console.log(`The winning numbers are ${winningNum1} and ${winningNum2}!`);
if (lottoNum1 == winningNum1 && lottoNum2 == winningNum2) {
console.log("You win BIG!");
}
else if (lottoNum1 == winningNum1 || lottoNum2 == winningNum2) {
console.log("You win SMALL!");
}
else {
console.log("You lose! Better luck next time!");
}
//

Task 3: Bonus - Fix Lotto Number Check

  • icon Submitting empty input for each lotto number will still allow the game to proceed, since each value evaluates to NaN.
  • icon Modify the condition by adding two more logical OR expressions to check whether either lotto number is NaN using a function called isNaN(). Google it to see how it works.

Task 4: Bonus - Add Another Lotto Win Condition

  • icon create another win condition using another else if statement if the lotto numbers match out of order.
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Chinese Zodiac Calendar ---
Enter your birth year: 1990
Birth year: 1990 - You are the year of the...horse.
Press enter to continue... [Enter]
--- Lottery Game ---
Rules: Pick a two lottery numbers ranging from 0 to 9
Match two numbers and win BIG!
Match one number in order and win SMALL!
Enter your 1st lottery number (0 to 9): 2
Enter your 2nd lottery number (0 to 9): 4
The winning numbers are 2 and 6!
You win SMALL!
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. How does using if, else if, else change the behavior of the program compared to using multiple, separate if statements? Describe a scenario where a separate if statement would be appropriate.
  2. In the Chinese Zodiac program, the else block handles the case where the input is invalid. How does this demonstrate the role of the else statement as a "catch-all" or "fallback" in your code?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete