Module 5 - Branching and Switch

Introduction

Flow control is a fundamental concept in JavaScript, as well as in most programming languages, that allows developers to manage the execution of code by making decisions and controlling the flow of instructions. It is an essential part of writing dynamic and interactive applications, enabling you to create logic that responds to different conditions and iterations. Flow control in JavaScript primarily involves the use of branching and looping structures to control the order of execution and make your programs more flexible and powerful.

Branching Structures

Branching structures in JavaScript are used to make decisions and execute different blocks of code based on certain conditions. The most commonly used branching structure in JavaScript is the if...else statement. It allows you to create two distinct paths of execution:

  • if Statement: The if statement is used to execute a block of code if a specified condition evaluates to true. If the condition is false, the code block within the if statement is skipped.
  • else Statement: The else statement is used in conjunction with an if statement to specify a block of code that is executed when the condition in the if statement is false.
  • else if Statement: The else if statement can be used to create a series of conditions to be checked in sequence, allowing you to execute different blocks of code depending on which condition is met.
  • switch Statement: The switch statement is another branching structure used when you have multiple conditions to evaluate. It is particularly useful when you want to compare a single value against multiple possible values and execute different code blocks accordingly.

Branching structures are vital for implementing logic in your JavaScript programs. They enable you to control what happens under different circumstances, making your code more adaptable and responsive to user input or changing data.



Comparison Operators

Comparison operators in JavaScript are used to compare two values or expressions, determining whether they are equal, not equal, greater than, less than, or a combination of these conditions. These operators return a Boolean value (true or false) based on the comparison. Here's a thorough description of all available comparison operators in JavaScript, along with their proper usage and examples:

Equality Operator (==):

The equality operator checks if two values are equal, performing type coercion if necessary (i.e., converting one or both values to a common type for comparison).
Usage: operand1 == operand2

Example:

let isEqual = 5 == '5'; // isEqual will be true (type coercion converts string '5' to the number 5 for comparison)

Inequality Operator (!=):

The inequality operator checks if two values are not equal, performing type coercion if necessary.
Usage: operand1 != operand2

Example:

let isNotEqual = 5 != '7'; // isNotEqual will be true (type coercion converts string '7' to the number 7 for comparison)

Strict Equality Operator (===):

The strict equality operator checks if two values are equal without type coercion; both the value and the data type must match.
Usage: operand1 === operand2

Example:

let isStrictEqual = 5 === 5; // isStrictEqual will be true (both values are numbers and equal)

Strict Inequality Operator (!==):

The strict inequality operator checks if two values are not equal without type coercion.
Usage: operand1 !== operand2

Example:

let isStrictNotEqual = 5 !== '5'; // isStrictNotEqual will be true (one value is a number, and the other is a string)

Greater Than Operator (>):

The greater than operator checks if the left operand is greater than the right operand.
Usage: operand1 > operand2

Example:

let isGreaterThan = 10 > 7; // isGreaterThan will be true

Less Than Operator (<):

The less than operator checks if the left operand is less than the right operand.
Usage: operand1 < operand2

Example:

let isLessThan = 3 < 6; // isLessThan will be true

Greater Than or Equal To Operator (>=):

The greater than or equal to operator checks if the left operand is greater than or equal to the right operand.
Usage: operand1 >= operand2

Example:

let isGreaterThanOrEqual = 5 >= 5; // isGreaterThanOrEqual will be true

Less Than or Equal To Operator (<=):

The less than or equal to operator checks if the left operand is less than or equal to the right operand.
Usage: operand1 <= operand2

Example:

let isLessThanOrEqual = 8 <= 10; // isLessThanOrEqual will be true

These comparison operators are crucial for making decisions in your JavaScript code. They are often used in conditional statements, such as if statements, to control the flow of your program based on the results of the comparisons. Understanding the differences between the equality operators and the strict equality operators is particularly important to avoid unexpected type coercion behavior.



If, Else If, and Else

In JavaScript, the if, else if, and else statements are fundamental components of branching structures that allow you to make decisions and control the flow of your code based on specified conditions. These statements are used to create conditional logic, where different blocks of code are executed depending on the evaluation of certain conditions. Below, I will provide detailed explanations of these statements along with examples and usage recommendations:

1. if Statement:

The if statement is used to execute a block of code if a specified condition evaluates to true. It is a fundamental building block of conditional logic.

Syntax:

if (condition) {
// Code to be executed if the condition is true
}

Example:

const age = 25;

if (age >= 18) {
console.log("You are an adult.");
}

Usage Recommendations:

  • Use the if statement when you want to execute a block of code based on a single condition.
  • It is the most basic form of conditional statement in JavaScript.

2. else if Statement:

The else if statement allows you to create a series of conditions to be checked in sequence. It is used when you need to handle multiple conditions, and only one of them should be executed.

Syntax:

if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}

Example:

const temperature = 25;

if (temperature > 30) {
console.log("It's hot outside.");
} else if (temperature > 20) {
console.log("It's warm outside.");
} else {
console.log("It's cool outside.");
}

Usage Recommendations:

  • Use else if when you have multiple conditions to evaluate in sequence.
  • else if statements provide a way to handle more complex decision-making scenarios.

3. else Statement:

The else statement is used in conjunction with an if statement to specify a block of code that is executed when the condition in the if statement is false. It is the catch-all condition.

Syntax:

if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

Example:

const loggedIn = true;

if (loggedIn) {
console.log("Welcome to your account.");
} else {
console.log("Please log in to access your account.");
}

Usage Recommendations:

  • Use the else statement when you have a default action to be taken when the condition in the if statement is false.
  • It ensures that there is always some code executed, even if none of the conditions in the if or else if statements are met.

Summary:

In JavaScript, the if, else if, and else statements are essential for creating conditional logic. They allow you to control the flow of your code based on conditions, making your programs more dynamic and responsive. When using these statements, it's crucial to consider the order of conditions and structure your logic to handle all possible scenarios effectively. These statements are versatile tools for decision-making in your JavaScript applications.



Switch

The switch statement is a powerful and flexible control structure in JavaScript used for making decisions based on the value of an expression. It provides an efficient way to handle multiple conditions by allowing you to compare a single value against multiple possible values. In this explanation, we'll delve into the switch statement, provide examples, and offer usage recommendations.

Syntax:

The basic syntax of the switch statement is as follows:

switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// ...
default:
// Code to execute if expression doesn't match any case
}
  • The switch statement begins with the keyword switch followed by an expression in parentheses. This expression is what you want to evaluate.
  • Inside the switch block, you define various case labels, each representing a possible value that the expression might match.
  • When a case label matches the value of the expression, the corresponding code block is executed, and the break statement is used to exit the switch block.
  • The default case is optional and is executed when none of the case labels match the expression.

Example:

const dayOfWeek = "Wednesday";

switch (dayOfWeek) {
case "Monday":
console.log("It's the start of the workweek.");
break;
case "Wednesday":
console.log("It's the middle of the workweek.");
break;
case "Friday":
console.log("It's the end of the workweek.");
break;
default:
console.log("It's not a workday.");
}

In this example, the switch statement evaluates the dayOfWeek variable and executes the corresponding block of code based on the value of dayOfWeek.

Usage Recommendations:

  • Multiple Comparisons: The switch statement is especially useful when you need to compare one value against multiple possible values. It's a cleaner and more efficient alternative to using multiple if...else if...else statements.
  • Exact Value Matching: switch performs strict comparison (===), which means it checks both value and data type. This can be beneficial when you want to make precise comparisons.
  • Use Default Case: Always include a default case. It provides a fallback action in case none of the case labels match the expression. This can help you avoid unintended behavior.
  • No Fall-Through: Unlike some other programming languages, JavaScript's switch statement does not "fall through" to the next case after executing a matching case. Each case is separate, and you should use the break statement to prevent unintended execution of subsequent cases.
  • Readable Code: Keep your switch statements concise and well-organized. If the logic in a case block becomes complex, consider encapsulating it in a separate function for better code readability.
  • Consider Using if...else: While switch is suitable for multiple comparisons based on the value of a single expression, for more complex conditional logic involving multiple expressions, if...else if...else statements may be more appropriate.

In conclusion, the switch statement is a valuable tool for handling multiple conditions in JavaScript. It provides an efficient and organized way to execute code based on the value of an expression. When used appropriately, it can make your code more readable and maintainable, particularly in situations where you have several values to compare.

Videos for Module 5 - Branching and Switch

There are no videos yet this term for this Module. Check back soon!

Activities for this Module

S5 - Number Guessing Game

Note: Sandbox assignments are designed to be formative activities that are somewhat open-ended. To get the most value, spend some time playing around as you code.

Instructions:

In this sandbox challenge, you will be creating a number guessing game.  When the page loads, the script on the page will generate a random number between 1 and 10. The user will see a form that allows them to enter a guess between 1 and 10. The script will compare the user's guess to the computer's secret number and either it will tell them ist is correct, or the following will happen:

  • The user will be told their guess is wrong.
  • The "encouragement message" will change to let them know which guess they are on.
  • The number they guessed will be added to an array and displayed to help them avoid duplicate guesses.

When the user runs out of guesses, they will see an alert and the page will reload.

For this challenge, start with the S5 Template file, and follow the comments in the document to add the code needed to complete the game. Along the way, you will see how both an if...else statement and a switch statement work in code.

Download the S5 Template File

When you are done, upload a screenshot of your code (not the page as it displays) to the forum.

 

A5 - Multiple Calculator

The Challenge

Ok - For this assignment, you will be creating from scratch. Let's say in your previous assignment you had a currency conversion calculator that changed Euros to USD. You might expand on that for this assignment and also include a USD to Euros calculator. 

Here is a description of what you need to include:

  • When the user opens the page, they should see two buttons. The buttons should be labeled to represent two different calculators. They should be labeled to represent the two calculators you chose.
  • When each of the buttons is clicked, it should show the corresponding calculator, and hide the other.
  • When a calculator is used, it should show the answers in a third div.
  • When calculators are switched, the answer div should be hidden.
  • BONUS: When the page background is clicked, hide all divs.

Constraints / Success Criteria

  • Each calculator should be on its own div.
  • Only one should ever be shown at a time.
  • Page must start showing only the two buttons and a heading.
  • Use CSS to make the page attractive and usable.
  • You must use at least one if...else statement in your code.

How to Submit

Submit your HTML file.