Scalable Business for Startups

Get the oars in the water and start rowing. Execution is the single biggest factor in achievement so the faster and better your execution.

+91 9472774549 thebytemind@gmail.com Looking for collaboration for your next creative project?

Chapter 5: Control Structures: Conditionals

Introduction

In programming, conditionals allow you to direct the flow of a program based on certain conditions. In JavaScript, conditional statements are crucial for creating interactive, decision-based programs. This chapter explores how to control program logic with conditionals, enabling dynamic responses to user input, data, and environment states.

5.1 Basics of Conditional Statements

In JavaScript, conditional statements determine whether a particular piece of code should execute. They typically use comparison operators (===, >, <, >=, <=, !==) and logical operators (&&, ||, !) to evaluate conditions.

5.2 The if Statement

The if statement is the simplest conditional, executing a block of code if the given condition evaluates to true.

Syntax:
if (condition) {
       // Code to execute if condition is true
    }
Example:
let temperature = 75;

if (temperature > 70) {
    console.log("It's a warm day!");
}
// Output: It's a warm day!

In this example, the if block only executes if temperature is above 70.

5.2.1 Complex Conditions with Logical Operators

Logical operators allow you to combine multiple conditions within a single if statement:

  • && (AND): Both conditions must be true.
  • || (OR): At least one condition must be true.
  • ! (NOT): Inverts the condition.
Example:
let isSunny = true;
let temperature = 80;

if (isSunny && temperature > 70) {
    console.log("Perfect day for a picnic!");
}
5.3 The else Statement

An else statement provides an alternative block of code if the if condition is false.

Syntax:
if (condition) {
    // Code if condition is true
} else {
    // Code if condition is false
}
Example:
let hour = 14;

if (hour < 12) {
    console.log("Good morning!");
} else {
    console.log("Good afternoon!");
}
// Output: Good afternoon!
5.4 The else if Statement

When multiple conditions need evaluation, else if statements allow cascading checks, executing different code for each condition that evaluates to true.

Syntax:
if (condition1) {
    // Code if condition1 is true
} else if (condition2) {
    // Code if condition2 is true
} else {
    // Code if no conditions are true
}
Example:
let score = 82;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: D");
}
// Output: Grade: B
5.5 The switch Statement

The switch statement simplifies checks for multiple values of a single variable. Each case represents a possible value, and default handles any unmatched cases.

Syntax:
switch (expression) {
    case value1:
        // Code if expression === value1
        break;
    case value2:
        // Code if expression === value2
        break;
    default:
        // Code if no cases match
}
Example:
let day = 4;
let dayName;

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

console.log(dayName);
// Output: Thursday
5.6 Real-World Examples of Conditionals
Example 1: User Authentication
let username = "admin";
let password = "12345";

if (username === "admin" && password === "12345") {
    console.log("Login successful!");
} else {
    console.log("Incorrect username or password.");
}
5.7 Best Practices with Conditionals
  • Simplify Logic: Avoid complex nested conditionals; refactor code into functions when possible.
  • switch for Multiple Cases: Use switch when handling multiple, known values of a single variable.
  • Combine Conditions Carefully: Be cautious with && and || to avoid logic errors.
  • Use Ternary Operators for Simple Conditions: A ternary operator can replace simple if-else structures for readability.
Example with Ternary:
let age = 20;
let category = age >= 18 ? "Adult" : "Minor";
console.log(category);
// Output: Adult
5.8 Exercises
  1. Write a program that accepts a username and password. If the username and password match stored values, print "Login successful"; otherwise, print "Invalid credentials."
  2. Create a grading system that uses else if statements to categorize scores (90+ is "A", 80-89 is "B", 70-79 is "C", etc.).
  3. Write a program that checks the value of a shopping cart. If the value is over $100, apply a 10% discount; if over $200, apply 20%.
  4. Using a switch statement, write a program that takes a number (1-7) as input and returns the corresponding weekday.
Summary
  • How to use if, else if, and else statements for decision-making.
  • How to simplify multi-case checks with switch.
  • The importance of clear, logical flow in conditional structures.