Explore Conditional Branching in JavaScript

CSSCSSBeginner
Practice Now

Introduction

In this lab, participants will dive deep into the world of conditional branching in JavaScript, exploring various techniques for making decisions and controlling program flow. The lab covers essential concepts such as single branch if statements, if...else logic, multi-condition statements, and switch statements, providing hands-on experience with different conditional structures.

Through practical coding exercises, learners will gain proficiency in implementing conditional logic, comparing different branching techniques, and understanding how to choose the most appropriate approach for specific programming scenarios. By working through step-by-step examples involving age verification, grade evaluation, and case handling, participants will develop a solid foundation in JavaScript's conditional programming capabilities.

Understand Single Branch if Statement

In this step, you'll learn about the basic single branch if statement in JavaScript, which allows you to execute code conditionally based on a specific condition.

First, let's create a JavaScript file to explore the single branch if statement. Open the WebIDE and create a new file named conditional-basics.js in the ~/project directory.

// Create a simple age verification example
let age = 18;

// Single branch if statement
if (age >= 18) {
  console.log("You are eligible to vote!");
}

In this example, the if statement checks if the age is greater than or equal to 18. If the condition is true, the code block inside the curly braces {} will be executed.

Let's run the script to see the output:

node ~/project/conditional-basics.js

Example output:

You are eligible to vote!

Now, let's try another example to demonstrate how the if statement works when the condition is false:

// Modify the previous file
let temperature = 15;

if (temperature < 10) {
  console.log("It's cold outside. Wear a jacket!");
}

In this case, since the temperature is 15 (which is not less than 10), nothing will be printed when you run the script.

Implement if...else Conditional Logic

In this step, you'll learn about the if...else conditional logic in JavaScript, which allows you to execute different code blocks based on whether a condition is true or false.

Open the WebIDE and create a new file named conditional-else.js in the ~/project directory. We'll create a simple example that demonstrates how if...else works:

// Create a simple grade evaluation example
let score = 75;

if (score >= 60) {
  console.log("Congratulations! You passed the exam.");
} else {
  console.log("Sorry, you did not pass the exam.");
}

In this example, the if...else statement checks if the score is greater than or equal to 60. If the condition is true, it prints a passing message. Otherwise, it prints a failing message.

Let's run the script to see the output:

node ~/project/conditional-else.js

Example output:

Congratulations! You passed the exam.

Now, let's modify the script to demonstrate the else part by changing the score:

// Modify the previous file
let score = 45;

if (score >= 60) {
  console.log("Congratulations! You passed the exam.");
} else {
  console.log("Sorry, you did not pass the exam.");
}

When you run this script, you'll see a different output:

Example output:

Sorry, you did not pass the exam.

Let's create another example to show how if...else can be used with different types of conditions:

// Add another example to the file
let isRaining = true;

if (isRaining) {
  console.log("Take an umbrella with you.");
} else {
  console.log("Enjoy the sunny day!");
}

This example shows how if...else can work with boolean conditions as well.

Create Multi-Condition if...else if...else Statements

In this step, you'll learn how to use multiple conditions with if...else if...else statements in JavaScript to handle more complex decision-making scenarios.

Open the WebIDE and create a new file named multi-condition.js in the ~/project directory:

// Create a grade classification example
let score = 85;

if (score >= 90) {
  console.log("Excellent! You got an A grade.");
} else if (score >= 80) {
  console.log("Great job! You got a B grade.");
} else if (score >= 70) {
  console.log("Good work! You got a C grade.");
} else if (score >= 60) {
  console.log("You passed. You got a D grade.");
} else {
  console.log("Sorry, you failed the exam.");
}

In this example, the if...else if...else statement checks multiple conditions in sequence. The first condition that evaluates to true will have its code block executed, and the remaining conditions will be skipped.

Let's run the script to see the output:

node ~/project/multi-condition.js

Example output:

Great job! You got a B grade.

Now, let's modify the score to see how different conditions work:

// Try different score scenarios
let score = 55;

if (score >= 90) {
  console.log("Excellent! You got an A grade.");
} else if (score >= 80) {
  console.log("Great job! You got a B grade.");
} else if (score >= 70) {
  console.log("Good work! You got a C grade.");
} else if (score >= 60) {
  console.log("You passed. You got a D grade.");
} else {
  console.log("Sorry, you failed the exam.");
}

When you run this script, you'll see a different output:

Example output:

Sorry, you failed the exam.

Let's create another example to demonstrate multi-condition logic with a different scenario:

// Weather condition example
let temperature = 25;

if (temperature > 30) {
  console.log("It's very hot outside.");
} else if (temperature > 20) {
  console.log("The weather is warm and pleasant.");
} else if (temperature > 10) {
  console.log("It's a bit cool today.");
} else {
  console.log("It's cold outside.");
}

This example shows how if...else if...else can be used to handle multiple conditions with different outcomes.

Use Switch Statement for Multiple Case Handling

In this step, you'll learn about the switch statement in JavaScript, which provides an alternative way to handle multiple conditions for a single variable.

Open the WebIDE and create a new file named switch-statement.js in the ~/project directory:

// Create a day of week example using switch statement
let day = 3;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break;
  default:
    console.log("Invalid day");
}

In this example, the switch statement checks the value of day. Each case represents a specific value, and the corresponding code block is executed when the value matches. The break statement prevents fall-through to the next case.

Let's run the script to see the output:

node ~/project/switch-statement.js

Example output:

Wednesday

Now, let's create another example to demonstrate the default case:

// Grade classification using switch statement
let grade = "B";

switch (grade) {
  case "A":
    console.log("Excellent performance!");
    break;
  case "B":
    console.log("Good job!");
    break;
  case "C":
    console.log("Satisfactory performance.");
    break;
  case "D":
    console.log("Needs improvement.");
    break;
  default:
    console.log("Invalid grade.");
}

When you run this script, you'll see:

Example output:

Good job!

Let's demonstrate how multiple cases can share the same code block:

// Weekend detection using switch statement
let day = 6;

switch (day) {
  case 6:
  case 7:
    console.log("It's the weekend!");
    break;
  default:
    console.log("It's a weekday.");
}

This example shows how you can handle multiple cases with the same action.

Compare and Choose Between if and Switch Statements

In this step, you'll learn the key differences between if statements and switch statements, and understand when to use each approach.

Open the WebIDE and create a new file named conditional-comparison.js in the ~/project directory:

// Comparing if and switch for different scenarios

// Scenario 1: Simple equality check
let fruit = "apple";

// Using if statement
if (fruit === "apple") {
  console.log("If Statement: It's an apple.");
} else if (fruit === "banana") {
  console.log("If Statement: It's a banana.");
} else {
  console.log("If Statement: Unknown fruit.");
}

// Using switch statement
switch (fruit) {
  case "apple":
    console.log("Switch Statement: It's an apple.");
    break;
  case "banana":
    console.log("Switch Statement: It's a banana.");
    break;
  default:
    console.log("Switch Statement: Unknown fruit.");
}

// Scenario 2: Complex conditions
let score = 85;

// if statement is better for complex conditions
if (score >= 90 && score <= 100) {
  console.log("Excellent grade (A)");
} else if (score >= 80 && score < 90) {
  console.log("Good grade (B)");
} else if (score >= 70 && score < 80) {
  console.log("Satisfactory grade (C)");
} else {
  console.log("Needs improvement");
}

// Switch is less suitable for range-based or complex conditions

Let's run the script to see the outputs:

node ~/project/conditional-comparison.js

Example output:

If Statement: It's an apple.
Switch Statement: It's an apple.
Good grade (B)

Key differences to remember:

  1. if statements are more flexible and can handle complex conditions
  2. switch statements are best for exact value matching
  3. if can compare different types and use complex logical operators
  4. switch is limited to strict equality checks

Let's create a final example to illustrate these points:

// Choosing between if and switch

function recommendConditional(input) {
  // Use switch for simple, exact value matching
  switch (input) {
    case "red":
    case "blue":
    case "green":
      console.log("Use switch for simple value checks");
      break;

    // Use if for more complex conditions
    default:
      if (typeof input === "number" && input > 0 && input < 100) {
        console.log("Use if for range and type checking");
      } else {
        console.log("Complex conditions are better with if statements");
      }
  }
}

recommendConditional("blue");
recommendConditional(50);

Summary

In this lab, participants explored conditional branching techniques in JavaScript, focusing on different types of conditional statements. The lab began with understanding single branch if statements, demonstrating how to execute code based on specific conditions such as age verification and temperature checks. Learners practiced creating simple conditional logic that allows code to run only when a specified condition is true.

The lab then progressed to more advanced conditional techniques, including if...else statements for handling two-way branching, multi-condition if...else if...else statements for complex decision-making, and switch statements for handling multiple case scenarios. Participants learned how to compare different conditional approaches, understanding the syntax and practical applications of each method in JavaScript programming.