Week 4: Guiding Your Code with Conditional Logic

Learn how to make your JavaScript programs make decisions using if, else if, else, and switch.

Explore Chapter 4

Chapter 4: Making Decisions with if, else if, else, and switch

Understanding Conditional Logic.

Conditional logic is essential for creating programs that can react differently based on various inputs or situations. It allows your code to follow different paths, making it dynamic and intelligent.

In JavaScript, the primary tools for conditional logic are the if, else if, and else statements, along with the switch statement for handling specific multi-way branching scenarios. These constructs evaluate conditions (expressions that result in true or false) to determine which block of code to execute.

Think about everyday decisions: "If the traffic light is green, go. Else if it's yellow, slow down. Else (if it's red), stop." Conditional statements in programming mirror this decision-making process.

if Statements: Executing Code Based on a Condition.

The if statement executes a block of code only if a specified condition evaluates to true (or a "truthy" value).

Syntax

if (condition) {
  // Code to be executed if the condition is true
  statement1;
  statement2;
  // ... more statements
}
  • The if keyword is followed by a condition enclosed in parentheses ().
  • The code block to be executed is enclosed in curly braces {}. While braces are optional for a single statement, it's strongly recommended to always use them for clarity and to avoid errors.

Example

let temperature = 25; // degrees Celsius

if (temperature > 20) {
  console.log("It's a warm day!");
}

In this example, "It's a warm day!" will be printed because the condition temperature > 20 is true.

else if Statements: Checking Multiple Conditions.

The else if statement allows you to check additional conditions if the preceding if (or else if) condition was false.

Syntax

if (condition1) {
  // Code for condition1 being true
} else if (condition2) {
  // Code executed if condition1 is false AND condition2 is true
} else if (condition3) {
  // Code executed if condition1 and condition2 are false AND condition3 is true
} // ... more else if statements can follow
  • Conditions are checked in order.
  • As soon as an if or else if condition evaluates to true, its block is executed, and the rest of the chain is skipped.

Example

let score = 78;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B"); // This block executes
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: D or F");
}

Since score >= 90 is false, it checks score >= 80, which is true. "Grade: B" is printed, and the remaining else if and else are skipped.

else Statements: Providing a Default Action.

The else statement provides a block of code that executes if *none* of the preceding if or else if conditions were true. It acts as a default or fallback case.

Syntax

if (condition1) {
  // Code for condition1 true
} else if (condition2) {
  // Code for condition1 false, condition2 true
} else {
  // Code executed if ALL preceding conditions (condition1, condition2) are false
}
  • An else statement is optional and must appear last in an if...else if... chain.
  • It does not have a condition associated with it.

Example

let hour = 20; // 8 PM

if (hour < 12) {
  console.log("Good morning!");
} else if (hour < 18) {
  console.log("Good afternoon!");
} else {
  console.log("Good evening!"); // This block executes
}

Truthy and Falsy Values.

In JavaScript, conditions don't strictly need to evaluate to true or false. Any value can be evaluated in a boolean context. Values that evaluate to true are called "truthy", and values that evaluate to false are called "falsy".

Falsy Values:

There are only a few falsy values in JavaScript:

  • false
  • 0 (zero)
  • -0 (minus zero)
  • 0n (BigInt zero)
  • "" (empty string)
  • null
  • undefined
  • NaN (Not a Number)

All other values, including non-empty strings ("hello"), non-zero numbers (42), objects ({}), and arrays ([]), are truthy.

Example:

let username = ""; // Falsy
let points = 0;    // Falsy
let userList = []; // Truthy (even though empty)

if (username) {
  console.log("Username exists."); // This won't run
} else {
  console.log("Please enter a username."); // This will run
}

if (points) {
  console.log("You have points!"); // This won't run
} else {
    console.log("No points yet."); // This will run
}

if(userList){
    console.log("User list exists (might be empty)."); // This WILL run
}

Understanding truthy/falsy is important for writing concise conditional checks.

switch Statement: Handling Multiple Specific Cases.

The switch statement provides an alternative way to execute different blocks of code based on the value of an expression. It's often cleaner than long if...else if...else chains when you're comparing a single value against multiple specific possibilities.

Syntax

switch (expression) {
  case value1:
    // Code to execute if expression === value1
    break; // Important: exits the switch
  case value2:
    // Code to execute if expression === value2
    break;
  // ... more cases
  default:
    // Code to execute if no case matches
}
  • The expression is evaluated once.
  • Its value is compared strictly (===) against the value of each case.
  • If a match is found, the code block associated with that case is executed.
  • The break statement is crucial. It stops the execution within the switch. If omitted, execution will "fall through" to the next case, which is usually unintended.
  • The default case is optional and executes if no other case matches.

Example

let day = new Date().getDay(); // Returns 0 (Sunday) to 6 (Saturday)
let dayName;

switch (day) {
  case 0:
    dayName = "Sunday";
    break;
  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;
  default: // Should not happen with getDay()
    dayName = "Invalid Day";
}
console.log("Today is " + dayName);

Conditional (Ternary) Operator: A Concise if-else.

The ternary operator is a shorthand way to write a simple if-else statement, especially useful for assigning a value based on a condition.

Syntax

condition ? valueIfTrue : valueIfFalse
  • If the condition is truthy, the expression evaluates to valueIfTrue.
  • If the condition is falsy, the expression evaluates to valueIfFalse.

Example

let age = 21;
let beverage = (age >= 18) ? "Beer" : "Juice";
console.log("Allowed beverage:", beverage); // Output: Allowed beverage: Beer

let isAuthenticated = false;
let greeting = isAuthenticated ? "Welcome back!" : "Please log in.";
console.log(greeting); // Output: Please log in.

While concise, avoid nesting ternary operators excessively as it can quickly become hard to read.

Nested if Statements: Conditions within Conditions.

You can place if, else if, and else statements inside the code blocks of other conditional statements. This allows for more complex decision-making logic based on multiple levels of conditions.

Syntax

if (outerCondition) {
  console.log("Outer condition is true.");
  if (innerCondition) {
    console.log("Inner condition is also true.");
  } else {
    console.log("Inner condition is false.");
  }
} else {
  console.log("Outer condition is false.");
}
  • Pay close attention to curly braces {} to define the scope of each block correctly.
  • Deeply nested conditionals can become difficult to read and debug. Consider if you can simplify the logic, perhaps by using logical operators (&&, ||) or by breaking the logic into separate functions.

Example

let userRole = "admin";
let isActive = true;

if (isActive) {
  console.log("User account is active.");
  if (userRole === "admin") {
    console.log("Admin access granted.");
  } else if (userRole === "editor") {
    console.log("Editor access granted.");
  } else {
    console.log("Standard user access.");
  }
} else {
  console.log("User account is inactive. Access denied.");
}
Syllabus